0

I have a specific route for a single page application that I want to cause the page to completely reload whenever the user enters or leaves this route.

    <Route
      key={routeKeyGen()}
      path="/example"
      component={Example}
      onEnter={onExampleRoute}
    />

I tried to do this by setting up onEnter to refresh the browser page:


const onExampleRoute = () => window.location.reload();

I quickly realized this was ridiculous when the page kept reloading over and over again. I don't think this handles when leaving the route, either.

Edit Here is the React Router v3 API for Route: https://github.com/ReactTraining/react-router/blob/v3/docs/API.md#route

Edit 2: There is an onLeave in the React Router v3 API for Route: https://github.com/ReactTraining/react-router/blob/v3/docs/API.md#onleaveprevstate

rpivovar
  • 3,150
  • 13
  • 41
  • 79
  • There is concept called server side rendering. Take a look at this article it explains how to server side render some routes. https://tylermcginnis.com/react-router-server-rendering/ – Majid Jan 22 '20 at 14:02
  • You need to consider a fact: With SPAs, when you open any route from your browser directly, e.g. `/about` your server will return your `index.html` file regardless of the route, and when the JS bundle loaded, then the react-router will show `/about` instead of the default `/`. So.. not that there are no workarounds to do the page refresh... but most probably, there are better ways to achieve what you wanna do without using the page reload. Giving some details about the purpose will help. – evolon Jan 22 '20 at 14:20
  • @evolon the reason I want to do this is to conditionally load in a vendor script in the index.html file so that a specific route does not load that script. It's not an ideal scenario and the ultimate goal would be to refactor how this vendor script is implemented, but I'm trying to set this up as a reloading route in the interim until the vendor script is implemented a different way. I don't have complete leeway on the solution since it's not a personal project. – rpivovar Jan 22 '20 at 14:28

1 Answers1

1

The simplest solution with pure React can be:

Load the script programmatically, in the component of the route

If this is your route.js file

<Route path="/path/you/want/to/load/js" component={Page.js} />

In the Page.js component:

class Page extends Component {

   ...

   componentDidMount () {
      const script = document.createElement("script");

      script.src = "https://path/to/your/file.js";
      script.async = true;
      script.onload = this.handleScriptLoad;

      document.body.appendChild(script);
   }

   handleScriptLoad = () => {
      // the script loaded!!!
   }

   ...
}

For more details, you can take a look at here: Adding script tag to React/JSX

evolon
  • 1,276
  • 1
  • 10
  • 18