reactjsreact-routerreact-router-dom

React Router not showing default homepage on pageload


I am just learning to use React Router and I've got my main App.js file looking like this:

function App() {
  return (
    <>
    <Router>
        <Navbar />
        <Switch>
          <Route  path="/resources" exact component={Resources} />
          <Route  path="/info" exact component={Info} />
          <Route  path="/" exact component={Home} />
        </Switch>
    </Router>
    </>
  );
}

The issue that I am having is that when the page initially loads (after "npm start" or upon visiting where it's deployed on github-pages) the Home component isn't displayed. However, when I navigate to a different route (via the Links in the Navbar component) the different route works as usual. I can then return to the Home component via the same Navbar and this time it does display. Then, when I refresh the page on the Home page it loads correctly. If I kill the development server and restart it, the homepage no longer loads. Any advice? Thanks.


Solution

  • function App() {
      return (
        <Router>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/resources" component={resources} />
            <Route path="/info" component={Info} />
            <Route path="*">
              <Redirect to="/" />
            </Route>
          </Switch>
        </Router>
      );
    }