react-router switch not working as expected

Bhavay Anand picture Bhavay Anand · Dec 29, 2018 · Viewed 7k times · Source

I'm learning react and got stuck at react-routes

consider the following:

import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";

import HelloWorld from "./HelloWorld.jsx";

const Root = () => {
  return (
    <BrowserRouter>
      <div>
        <Switch>
          <Route path="/" exact component={HelloWorld} />
          <Route component={NoMatch} />
        </Switch>
      </div>
    </BrowserRouter>
  );
};

function NoMatch({ location }) {
  return (
    <div>
      <h3>
        No match found
      </h3>
    </div>
  );
}

export default Root;

on '/' this route, it renders HelloWorld component as expected but on other routes for examples abc it displays Cannot GET /abc instead of No match found

Answer

Deryck picture Deryck · Dec 29, 2018

This happens because your server is not set up to handle those routes specifically. The server it what determines what exists and what doesn't - react-router is just a tool to exploit it a bit.

Fix 1

You can avoid this issue by importing HashRouter from the react-router-dom package, rather than BrowserRouter.

The result will be routing based on URLs with a #/ prepending the route itself. So your route of / will now actually be #/.

Fix 2

Set up a reverse proxy (nginx) as the intermediary to serve your page from the Node.js server. Use a broad wildcard or get specific if you know you need more specific configurations. It will pass along the request URI/path to node still but not try to use them as separate endpoints each time or read files from the file system.