react-mixpanel-browser
React providers for mixpanel-browser using the Context API.
Installation
Usage
-
Create a project in Mixpanel then add the token to ./.env
:
REACT_APP_MIXPANEL_TOKEN=<token>
-
Intialize Mixpanel with any custom configuration in ./src/index.jsx
:
import React from 'react';
import ReactDOM from 'react-dom';
import { init as initMixpanel } from 'react-mixpanel-browser';
import App from './App';
initMixpanel({/* custom configuration */});
ReactDOM.render(<App />, document.getElementById('root'));
-
Access the context using either the useMixpanel()
hook (stateless components only) or the withMixpanel()
High-Order Component. The value provided will be either an instance of MixpanelLib or null
if a token was not provided; useful for untracked environments.
Examples
Usage with useMixpanel()
Hook
import React from 'react';
import { useMixpanel } from 'react-mixpanel-browser';
const App = (props) = {
const mixpanel = useMixpanel();
// Note that mixpanel will be null if a token has not been configured
mixpanel && mixpanel.track('My Event', {
my_custom_prop: 'foo',
});
return <div>This page was tracked in Mixpanel</div>;
};
export default App;
Usage with withMixpanel()
High-Order Component
import React from 'react';
import { withMixpanel } from 'react-mixpanel-browser';
class App extends Component {
render() {
const { mixpanel } = this.props;
// Note that mixpanel will be null if a token has not been configured
mixpanel && mixpanel.track('My Event', {
my_custom_prop: 'foo',
});
return <div>This page was tracked in Mixpanel</div>;
}
}
export default withMixpanel(App);