Search code examples
javascriptreactjsreact-routergoogle-tag-managerreact-router-dom

React Router Link reloading page : Conflict with external event


I'm using React Router's Link component to handle page transition in my app.

My app is included in an external web page, which has some scripts (namely Google Tag Manager) that define events on links on the document level.

This causes a conflict with Link events : page is always reloading when clicking on a link.

I tried to stop propagation on my Link component with an onClick callback, with no luck : <Link onClick={(e) => { e.stopPropagation(); }} [...]>...</Link>

I see that Link events are also defined on the document level, so I don't know how to stop the external events.

Any clue on this one ?

Thank you !


Solution

  • I faced quite the similar issue on one of my apps and I think that the solution is to avoid using the react-router <Link /> component if you can.

    Instead of using the <Link /> component, I used the withRouter() HOC provided by react-router :

    What you wrote :

    Class MyComponent extends React.Component{
      <Link onClick={(e) => { e.stopPropagation(); }} [...]>
        ...
      </Link>
    }
    
    export default MyComponent;
    

    Can be replaced by :

    Class MyComponent extends React.Component{
    
      navigate = (event, location) => {
        event.preventDefault();
        this.props.history.push(location);
      }
    
      <a onClick={(e, href) => { this.navigate(e, href) }} [...]>
        ...
      </a>
    }
    
    export default withRouter(MyComponent);
    

    This should prevent your link to catch others event at the document level and achieve the same result as <Link /> component.