javascriptreactjsreact-routerreact-router-domreact-component

react-router switch not working as expected


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


Solution

  • The code works just fine if you used create-react-app for setting up the react project but if you're using webpack configurations for manually setting up the project it requires devServer: {historyApiFallback: true,} for react routes to work.