Instalar Google Analytics en una web que usa React

npm i react-ga

Tracking.js

import { useEffect } from 'react';
import ReactGA from 'react-ga';
import { useLocation } from 'react-router';


export default () => {
    const location = useLocation();

    useEffect(() => {
        ReactGA.initialize('GA-TRACKING-CODE!!!');
    }, []);

    useEffect(() => {
        ReactGA.pageview(location.pathname);
    }, [location]);

    return null;
};

routes.js

import { BrowserRouter, Route, Switch } from 'react-router-dom';
import NavigationBar from '../components/navbar';
import Tracking from './tracking';

import Home from '../pages/home';
import SillaCoche from '../pages/silla-coche';

export default () => (
    <BrowserRouter basename={process.env.PUBLIC_PATH}>
        <NavigationBar />
        <Tracking />
        <Switch>

            <Route exact path="/" component={Home} />
            <Route exact path="/sillitas-bebe-coche/" component={SillaCoche} />

            <Route path="*" component={() => <div>404</div>} />
        </Switch>
    </BrowserRouter>
);
← Compilar (build) una aplicación de React
Styleguidist →

Aviso Legal | Política de privacidad