1
2
import { AnalyticsBrowser } from '@june-so/analytics-next' ;
3
4
5
let analytics = AnalyticsBrowser . load ( {
6
writeKey : 'YOUR_WRITE_KEY' ,
7
} ) ;
Copy Using React
Implement a hook that can be used throughout your React app:
1
import { useEffect , useState } from 'react' ;
2
import { AnalyticsBrowser } from '@june-so/analytics-next' ;
3
4
export function useJune ( writeKey ) {
5
const [ analytics , setAnalytics ] = useState ( undefined ) ;
6
7
useEffect ( ( ) => {
8
const loadAnalytics = async ( ) => {
9
let response = AnalyticsBrowser . load ( {
10
writeKey ,
11
} ) ;
12
setAnalytics ( response ) ;
13
} ;
14
loadAnalytics ( ) ;
15
} , [ writeKey ] ) ;
16
17
return analytics ;
18
}
Copy Now you can use the hook in any component, like:
1
import { useCallback } from 'react' ;
2
import { useJune } from './useJune' ;
3
4
function PurchaseButton ( ) {
5
const analytics = useJune ( 'YOUR_WRITE_KEY' ) ;
6
7
const trackPurchase = useCallback ( ( ) => {
8
if ( analytics ) analytics . track ( 'Purchase Event' ) ;
9
} , [ analytics ] ) ;
10
11
return < button onClick = { trackPurchase } > Purchase coat < / button > ;
12
}
Copy Using NextJS
For a NextJS app, the best approach is installing the NPM package rather than using the inlined script. Tracking is rather similar to the React example above. You can reuse the hook above in your NextJS app, here's how:
1
import { useCallback } from 'react' ;
2
import { useJune } from './useJune' ;
3
4
function PurchaseButton ( ) {
5
const analytics = useJune ( 'YOUR_WRITE_KEY' ) ;
6
7
const trackPurchase = useCallback ( ( ) => {
8
if ( analytics ) analytics . track ( 'Purchase Event' ) ;
9
} , [ analytics ] ) ;
10
11
return < button onClick = { trackPurchase } > Purchase coat < / button > ;
12
}
Copy For tracking pageview events, you can do the following:
1
import { useEffect } from 'react' ;
2
import { useRouter } from 'next/router' ;
3
4
export default function MyApp ( { Component , pageProps } ) {
5
const analytics = useJune ( 'YOUR_WRITE_KEY' ) ;
6
const router = useRouter ( ) ;
7
8
useEffect ( ( ) => {
9
const handleRouteChange = ( url , { shallow } ) => {
10
if ( analytics ) analytics . page ( url ) ;
11
} ;
12
13
router . events . on ( 'routeChangeStart' , handleRouteChange ) ;
14
15
return ( ) => {
16
router . events . off ( 'routeChangeStart' , handleRouteChange ) ;
17
} ;
18
} , [ analytics ] ) ;
19
20
return < Component { ... pageProps } / > ;
21
}
Copy