Search code examples
javascriptreactjswordpressreact-routerurl-routing

React Router - Getting a page not found when not explicitly arriving at a dynamic route URL via a link or history.push


I'm trying to troubleshoot why I'm getting a "Page Not Found" / 404 page(?) in my application.

I have a router set up as follows:

<Router>
  <Search/>
  <Switch>
    <Route exact path="/cafes" component={ListView} />
    <Route
      path="/cafes/results/:loc"
      component={Results}
     />
     <Route component={NotFound} />
  </Switch>
</Router>

If I use the <Search> component, it will call the results route via this code:

this.props.history.push({
      pathname: `/cafes/results/${searchAddress}`,
    });

and that <Results> page component will successfully display search results. It will have a URL like: http://myurl.com/cafes/results/Los%20Angeles%2C%20CA%2C%20USA.

However, if I refresh the page, I get a page not found.

The <NotFound> component, from my understanding, should catch any routes that don't match the ones above it, but that's not happening.

It is a react app running within a Wordpress setup for which any URL starting with cafes should be suppressed from Wordpress's setup (though I don't know much about that bit, I didn't set it up). Is it possible that the issue is related to Wordpress, or have I messed something up within my react-router setup?


Solution

  • It's not a client-side (React or whatever) issue. A proof of this is the fact that all works while you stay on client (so: calling .push API) but as soon as you reload you go the the server.

    You must configure your front web server to always publish your page for every location under /cafes.

    This is commonly done by using an Apache/NGINX configuration.

    An NGINX example could be:

    location / {
      root /path/to/your/build/directory
      try_files $uri $uri/ /index.html =404;
    }
    

    I'm not sure is Wordpress can do this for you (but I'm not sure that's would be a good idea anyway)