score:99
keep a reference to your history object. i.e.
import { createbrowserhistory } from 'history';
var history = createbrowserhistory();
reactdom.render((
<router history={history}>
[...]
then add a listener to record each pageview. (this assumes you've already set up the window.ga
object in the usual manner.)
history.listen((location) => {
window.ga('set', 'page', location.pathname + location.search);
window.ga('send', 'pageview');
});
score:0
basic react-ga implementation with your index.js
var reactga = require('react-ga'); // require the react-ga module
reactga.initialize('your-ua-id-here'); // add your ua code
function logpageview() { // add this function to your component
reactga.set({ page: window.location.pathname + window.location.search });
reactga.pageview(window.location.pathname + window.location.search);
}
react.render((
<router history={createbrowserhistory()} onupdate={logpageview} > // insert onupdate props here
<route path="/" component={app}>
<indexroute component={home} onleave={closeheader}/>
<route path="/about" component={about} onleave={closeheader}/>
<route path="/gallery" component={gallery} onleave={closeheader}/>
<route path="/contact-us" component={contact} onleave={closeheader}>
<route path="/contact-us/:service" component={contact} onleave={closeheader}/>
</route>
<route path="/privacy-policy" component={privacypolicy} onleave={closeheader} />
<route path="/feedback" component={feedback} onleave={closeheader} />
</route>
<route path="*" component={nomatch} onleave={closeheader} />
</router>), document.getelementbyid('root'));
score:0
based on @david-l-walsh and @bozdoz suggestions
i created a hoc that execute the window.ga('set','page','{currenturl})
and window.ga('send', 'pageview');
function and is easly used directly in the router page...
this is the hoc:
import react from 'react';
import { history } from '../../store'; // or wherever you createbrowserhistory(); invokation is
function withgahistorytrack(wrappedcomponent) {
return class extends react.component {
constructor(props) {
super(props);
}
componentdidmount() {
const { location } = history;
const page = location.pathname + location.search;
if (typeof window.ga === 'function') {
window.ga('set', 'page', page);
window.ga('send', 'pageview');
}
}
render() {
return <wrappedcomponent {...this.props} />;
}
};
}
export default withgahistorytrack;
and is used this way in the router page:
<route
path={'yourpath'}
component={withgahistorytrack(yourcomponent)}
exact
/>
score:0
for dynamically updating url on some event (like onclick etc), following can be used:
//imports
import reactga from "react-ga";
import { createbrowserhistory } from "history";
// add following on some event, like onclick (depends on your requirement)
const history = createbrowserhistory();
reactga.initialize("<your-ua-id-here>");
reactga.pageview(history.location.pathname);
score:1
if you use hash or browser history you can do:
import trackinghit from 'tracking';
import { router, browserhistory } from 'react-router';
browserhistory.listen(trackinghit);
// or
import { router, hashhistory } from 'react-router';
hashhistory.listen(trackinghit);
where ./tracking.es6
export default function(location) {
console.log('new page hit', location.pathname);
// do your shizzle here
}
score:2
first, in your index.js set onupdate function to call ga
import ga from 'ga.js';
onupdate() {
console.log('=====ga=====>', location.pathname);
console.log('=====ga_tracking_code=====>', ga_tracking_code);
ga("send", "pageview", location.pathname);
}
render() {
return (
<router onupdate={this.onupdate.bind(this)}>...</router>
);
}
and ga.js:
'use strict';
if(typeof window !== 'undefined' && typeof ga_tracking_code !== 'undefined') {
(function(window, document, script, url, r, tag, firstscripttag) {
window['googleanalyticsobject']=r;
window[r] = window[r] || function() {
(window[r].q = window[r].q || []).push(arguments)
};
window[r].l = 1*new date();
tag = document.createelement(script),
firstscripttag = document.getelementsbytagname(script)[0];
tag.async = 1;
tag.src = url;
firstscripttag.parentnode.insertbefore(tag, firstscripttag);
})(
window,
document,
'script',
'//www.google-analytics.com/analytics.js',
'ga'
);
var ga = window.ga;
ga('create', ga_tracking_code, 'auto');
module.exports = function() {
return window.ga.apply(window.ga, arguments);
};
} else {
module.exports = function() {console.log(arguments)};
}
score:2
i suggest using the segment analytics library and following the react quickstart guide to track page calls using the react-router library. you can allow the <route />
component to handle when the page renders and use componentdidmount
to invoke page
calls. the example below shows one way you could do this:
const app = () => (
<div>
<switch>
<route exact path="/" component={home} />
<route path="/about" component={about} />
</switch>
</div>
);
export default app;
export default class home extends component {
componentdidmount() {
window.analytics.page('home');
}
render() {
return (
<h1>
home page.
</h1>
);
}
}
i’m the maintainer of https://github.com/segmentio/analytics-react. with segment, you’ll be able to switch different destinations on-and-off by the flip of a switch if you are interested in trying multiple analytics tools (we support over 250+ destinations) without having to write any additional code. 🙂
score:3
here is a simplest way to track all paths with some work arounds:
npm i --save history react-ga
create a file history.js
import { createbrowserhistory } from "history"
import reactga from "react-ga"
reactga.initialize(process.env.react_app_ga)
const history = createbrowserhistory()
history.listen((location) => {
reactga.pageview(location.pathname)
})
// workaround for initial visit
if (window.performance && (performance.navigation.type === performance.navigation.type_navigate)) {
reactga.pageview("/")
}
export default history
and then import it to where is set your router
import history from "./history"
...
class route extends component {
render() {
return (
<router history={history}>
<switch>
<route path="/" exact component={homepage} />
...
</switch>
</router>
)
}
export default route
references:
score:6
always go with the library's recommended way
in the react-ga documentation, they have added a community component recommended for using with react router: https://github.com/react-ga/react-ga/wiki/react-router-v4-withtracker
implementation
import withtracker from './withtracker';
reactdom.render(
<provider store={store}>
<connectedrouter history={history}>
<route component={withtracker(app, { /* additional attributes */ } )} />
</connectedrouter>
</provider>,
document.getelementbyid('root'),
);
code
import react, { component, } from "react";
import googleanalytics from "react-ga";
googleanalytics.initialize("ua-0000000-0");
const withtracker = (wrappedcomponent, options = {}) => {
const trackpage = page => {
googleanalytics.set({
page,
...options,
});
googleanalytics.pageview(page);
};
// eslint-disable-next-line
const hoc = class extends component {
componentdidmount() {
// eslint-disable-next-line
const page = this.props.location.pathname + this.props.location.search;
trackpage(page);
}
componentdidupdate(prevprops) {
const currentpage =
prevprops.location.pathname + prevprops.location.search;
const nextpage =
this.props.location.pathname + this.props.location.search;
if (currentpage !== nextpage) {
trackpage(nextpage);
}
}
render() {
return <wrappedcomponent {...this.props} />;
}
};
return hoc;
};
export default withtracker;
score:12
i like how mark thomas müller suggests here:
in your index.js
import reactga from 'react-ga'
reactga.initialize('youranalyticsid')
reactdom.render(<app />, document.getelementbyid('root'))
where your routes are:
import react, { component } from 'react'
import { router, route } from 'react-router-dom'
import createhistory from 'history/createbrowserhistory'
import reactga from 'react-ga'
const history = createhistory()
history.listen(location => {
reactga.set({ page: location.pathname })
reactga.pageview(location.pathname)
})
export default class approutes extends component {
componentdidmount() {
reactga.pageview(window.location.pathname)
}
render() {
return (
<router history={history}>
<div>
<route path="/your" component={your} />
<route path="/pages" component={pages} />
<route path="/here" component={here} />
</div>
</router>
)
}
}
short, scalable and simple :)
score:18
i would suggest using the excellent react-router-ga
package that is extremely lightweight and easy to configure, especially when using the browserrouter
wrapper.
import the component:
import analytics from 'react-router-ga';
then simply add the <analytics>
within your browserrouter
:
<browserrouter>
<analytics id="ua-analytics-1">
<switch>
<route path="/somewhere" component={somecomponent}/>
</switch>
</analytics>
</browserrouter>
score:20
note if you're using the react-router-dom
package from react-router-4
you can handle this like so:
import { router, route } from 'react-router-dom';
import { createbrowserhistory } from 'history';
const history = createbrowserhistory();
const initga = (history) => {
(function(i,s,o,g,r,a,m){i['googleanalyticsobject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new date();a=s.createelement(o),
m=s.getelementsbytagname(o)[0];a.async=1;a.src=g;m.parentnode.insertbefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'your_identifier_here', 'auto');
ga('send', 'pageview');
history.listen((location) => {
console.log("tracking page view: " + location.pathname);
ga('send', 'pageview', location.pathname);
});
};
initga(history);
class app extends component { //eslint-disable-line
render() {
return
(<router history={history} >
<route exact path="/x" component={x} />
<route exact path="/y" component={y} />
</router>)
}
}
note that this requires you to install the history
package (npm install history
). this is already a dependency of react-router-dom so you're not adding any page weight here.
also note: it is not possible to use the browserrouter component and instrument your ga tracking this way. this is okay because the browserrouter component is just a really thin wrapper around the router object. we recreate the browserrouter functionality here with <router history={history}>
where const history = createbrowserhistory();
.
score:32
i'm using react router v4 and the google analytics global site tag, which appears to be recommended at the time of writing this.
and here's my solution:
create a component wrapped in withrouter from react-router-dom
:
import react from 'react';
import { withrouter } from 'react-router-dom';
import { ga_tracking_id } from '../config';
class googleanalytics extends react.component {
componentwillupdate ({ location, history }) {
const gtag = window.gtag;
if (location.pathname === this.props.location.pathname) {
// don't log identical link clicks (nav links likely)
return;
}
if (history.action === 'push' &&
typeof(gtag) === 'function') {
gtag('config', ga_tracking_id, {
'page_title': document.title,
'page_location': window.location.href,
'page_path': location.pathname
});
}
}
render () {
return null;
}
}
export default withrouter(googleanalytics);
simply add the component within your router (i believe ideally after any routes that would be matched and any switch components, because the analytics function should not be priority over your site rendering):
import react from 'react';
import { browserrouter as router, route, switch } from 'react-router-dom';
import indexpage from './indexpage';
import notfoundpage from './notfoundpage';
import googleanalytics from './googleanalytics';
const app = () => (
<router>
<switch>
<route exact path="/" component={indexpage} />
<route component={notfoundpage} />
</switch>
<googleanalytics />
</router>
);
as stated:
withrouter will re-render its component every time the route changes with the same props as render props
so when the route changes, the googleanalytics
component will update, it will receive the new location as props, and history.action
will be either push
for a new history item or pop
to signal going backwards through the history (which i think shouldn't trigger a page view, but you can adjust the if statements in componentwillupdate
as you see fit (you could even try componentdidupdate
with this.props
instead, but i'm unsure which is better)).
score:34
given that google analytics is loaded and initialised with a tracking id.
here is a solution for react-router version 4 using the <route>
component to track page views.
<route path="/" render={({location}) => {
if (typeof window.ga === 'function') {
window.ga('set', 'page', location.pathname + location.search);
window.ga('send', 'pageview');
}
return null;
}} />
you simply render this component inside the <router>
(but not as a direct child of a <switch>
).
what happens is that whenever the location prop changes it causes a re-render of this component (not actually rendering anything) that fire a pageview.
score:48
since react-router v5.1.0
this can be solved a lot easier with uselocation
.
usepagetracking.js
import { useeffect} from "react";
import { uselocation } from "react-router-dom";
import reactga from "react-ga";
const usepagetracking = () => {
const location = uselocation();
useeffect(() => {
reactga.initialize("ua-000000000-0");
reactga.pageview(location.pathname + location.search);
}, [location]);
};
export default usepagetracking;
app.js
const app = () => {
usepagetracking();
return (...);
};
see also:
here's a bit smarter version:
usepagetracking.js
import { useeffect, usestate } from "react";
import { uselocation } from "react-router-dom";
import reactga from "react-ga";
const usepagetracking = () => {
const location = uselocation();
const [initialized, setinitialized] = usestate(false);
useeffect(() => {
if (!window.location.href.includes("localhost")) {
reactga.initialize("ua-000000000-0");
}
setinitialized(true);
}, []);
useeffect(() => {
if (initialized) {
reactga.pageview(location.pathname + location.search);
}
}, [initialized, location]);
};
export default usepagetracking;
Source: stackoverflow.com
Related Query
- How to set up Google Analytics for React-Router?
- How to set up analytics on React Native for iOS
- How to set up Google Analytics 4 for React-Router?
- How to set active only one link with react router for multiple url state?
- How to set the DefaultRoute to another Route in React Router
- How to set NODE_ENV from package.json for react
- How to set headers for a React app created using 'create-react-app'
- React Router with - Ant Design Sider: how to populate content section with components for relevant menu item
- How to set React default props for object type
- How to set placeholder for dropdown in react js?
- How would I test for a react router route param in react-testing-library?
- How to implement scroll restoration for React Router SPA
- How do you set the Typescript type for useRef hook in React Native?
- How to set the Google Analytics cookie only after another consent cookie is set and "true"?
- How to make React input onChange set state only after onChange stops firing for set time?
- How To Configure React 360 for Google Cardboard
- how do I set logging levels on Android, for react native?
- how to set font size for different IOS devices in react native
- React router 4: How to wait for a promise to resolve, inside render method of Route?
- Difficulty installing Google Tag Manager in React for Google Analytics
- How to set display name for a React class (ES6)?
- React Cookie + ReactJS: How to set expiration time for a cookie?
- How can I programmatically set the user details for Launch Darkly in my react app
- React : How to stop re-rendering component or making an API calls on router change for the same route
- React semantic UI: How to set focus for input field of dropdown element
- React router activeClassName doesnt set active class for child routes
- How to correctly set up React Router with multilanguage/multiple index.html files?
- How do I set a default value for a select menu in my React form component?
- JSDoc: How to set @param for React element as a function param?
- React Router BrowserRouter History Push & Google Analytics
More Query from same tag
- Handling Events in React with Arrow Functions as variable or function?
- Building a React-Electron app using electron-builder, index.js loads inside pre tags
- Need help configuring react-hot-loader
- Is there some way where I could query this Map where I will only retrieve the data of those less than 5?
- Opacity transition affecting child with backdrop-filter
- Activating 2 different calls on react onClick
- How to handle percentage sign in table names when fetching data
- ResizableBox doesn't wrap contents
- Is there a way to debug react interactively
- Is there better solution than string.split() to pick first two lines from text chunk in ES6
- How To Change Color Of <td> element depending on value
- Regex time field validation fails in ReactJS
- React app, componentDidUpdate - jumping list, infinite loop
- [REACT]Material-ui multiple snackbar
- How to set alias path via webpack in CRA (create-react-app) and craco?
- How to require an additional charge for the first-time users in stripe subscription?
- How to fix an import error using a Match object in React Router
- What is the main difference between Mobx.inject an Mobx.observer when connecting stores?
- Creating a Toolbar with both Left and Right Justified Elements with Material UI and React.js
- Route not functioning as expected on React
- How can I center the text in the headers for an AG-grid control?
- materil-ui how to push the button very bottom of the paper area
- In React Project, how to change and customize node modules
- React button active style
- Passing data to react-vega
- Antd File upload not getting reset
- Difference between a function and a stateless component?
- returning 3 arrays from a react custom hook
- CKEditor 4 changes html div tag to p tag
- How to get input data from django request.POST