Skip to content

Instantly share code, notes, and snippets.

@arasmussen
Last active November 11, 2021 18:49
Show Gist options
  • Save arasmussen/c5019612adafa3dc33387f56911b6e73 to your computer and use it in GitHub Desktop.
Save arasmussen/c5019612adafa3dc33387f56911b6e73 to your computer and use it in GitHub Desktop.
Canny: Identifying your users with React
import PropTypes from 'prop-types';
import { Component } from 'react';
const AppID = 'Your App ID';
function loadCannySDK() {
!function(w,d,i,s){function l(){if(!d.getElementById(i)){var f=d.getElementsByTagName(s)[0],e=d.createElement(s);e.type="text/javascript",e.async=!0,e.src="https://canny.io/sdk.js",f.parentNode.insertBefore(e,f)}}if("function"!=typeof w.Canny){var c=function(){c.q.push(arguments)};c.q=[],w.Canny=c,"complete"===d.readyState?l():w.attachEvent?w.attachEvent("onload",l):w.addEventListener("load",l,!1)}}(window,document,"canny-jssdk","script");
}
export default class CannyContainer extends Component {
static contextTypes = {
viewer: PropTypes.shape({
_id: PropTypes.string,
avatarURL: PropTypes.string,
companies: PropTypes.arrayOf(PropTypes.shape({
_id: PropTypes.string,
monthlySpend: PropTypes.number,
name: PropTypes.string,
})),
email: PropTypes.string,
name: PropTypes.string,
}),
};
componentDidMount() {
loadCannySDK();
const { viewer } = this.context;
if (!viewer || !viewer._id) {
return;
}
Canny('identify', {
appID: AppID,
user: {
...(viewer.avatarURL && {
avatarURL: viewer.avatarURL,
}),
companies: viewer.companies.map((company) => ({
created: (new Date(company.created)).toISOString(),
id: company._id,
monthlySpend: company.monthlySpend / 100,
name: company.name,
})),
created: (new Date(viewer.created)).toISOString(),
email: viewer.email,
id: viewer._id,
name: viewer.name,
},
});
}
render() {
return this.props.children;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment