skip to Main Content

If I want to use Google analytics and at the same time make my site SEO friendly in React, what is the best way?

At the moment I use react-router and a flux pattern where I change the route and then in componentDidMount I fire an action that loads my data through ajax and then updates the store which emits the change and finally I re-render the components that are affected. During the ajax loading I dispatch an event so that my store knows ajax is loading and render a spinner in my component.

I have noticed that when I send my tracking data to Google the ajax has not finished loading and I only send the new page URL not the title or any other data which I load through ajax (I guess this is bad from an SEO perspective and it’s definitely bad for my GA data).

This is my GA setup (I use react-ga):

Router.run(routes, Router.HistoryLocation, function(Handler, state) {
    ga.pageview(state.pathname);
    React.render(<Handler />, document.body);
});

Typical component setup (which allows me to render the correct data based on the URL):

componentDidMount: function() {
    ItemStore.addChangeListener(this._onChange);

    if(itemSlug) {
        ItemActions.loadItemBySlug(this.props.slug);
    }
}

I want to be able to have a single point of GA tracking if that is possible. I also want the SEO handling to be correct for the page:

  • Page title
  • OG data
  • H1
  • etc …

What is the best approach to solve this?

Should I use the willTransitionTo option in react-router for this? (is it possible to use a loading spinner if I opt for this solution?)

statics: {
    willTransitionTo: function (transition, params, query, callback) {
        // LOAD AJAX HERE ?
        callback();
    }
}

How would I go about the willTransistionTo solution in a proper way, can’t seem to find any good examples that relate?

Should I add more code, or is it clear what I’m trying to achieve?

2

Answers


  1. Trigger the ga.pageview after the store gets the new data and renders.

    Login or Signup to reply.
  2. The appropriate way to handle SEO in react is to render at the server side isomorphically with React.renderToString, so that any search engine will see the page in its complete state, rather than just Google’s spider and only on those occasions when you manually call it.

    This was one of the original design criteria of React.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search