How to include google analytics in preact?

Member

by rollin , in category: Third Party Scripts , a month ago

How to include google analytics in preact?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , a month ago

@rollin 

To include Google Analytics in a Preact application, you can follow these steps:

  1. Create a Google Analytics account if you don't already have one.
  2. Get the tracking ID from Google Analytics. It looks like "UA-XXXXXXXXX-X".
  3. Install the react-ga library by running the following command in your terminal:
1
npm install react-ga


  1. In your Preact application, create a new file called analytics.js and add the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import ReactGA from 'react-ga';

export const initGA = () => {
    ReactGA.initialize('UA-XXXXXXXXX-X');
};

export const logPageView = () => {
    ReactGA.set({ page: window.location.pathname });
    ReactGA.pageview(window.location.pathname);
};


Replace 'UA-XXXXXXXXX-X' with your actual tracking ID.

  1. Import the analytics.js file in your main Preact component (usually App.js) and call initGA() function in the componentDidMount() method:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import { Component } from 'preact';
import { initGA, logPageView } from './analytics.js';

class App extends Component {
    componentDidMount() {
        initGA();
        logPageView();
    }

    render() {
        return <div>Your Preact App</div>;
    }
}

export default App;


  1. Throughout your Preact application, you can use the logPageView() function to track page views. For example, you can call logPageView() in the componentDidMount() method of each component to track the page view for that component.


That's it! Google Analytics tracking should now be included in your Preact application. Remember to test it by navigating to different pages and checking the Google Analytics dashboard for data.