Search code examples
reactjsreact-routerreach-router

React Router not switching to non-base routes


I'm setting up React Router in a project that was previously using Reach Router.

Before, the routes looked like this with Reach:

import { Router } from '@reach/router';

...

<Router>
      {anon ? <AnonHomepage /> : <Homepage />}
      <Explore path="explore/:category" />
</Router>

And then, switching to React Router, I have my file set up like this:

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

...

<BrowserRouter>
      <Switch>
        {anon ? (
          <Route path="/" component={AnonHomepage} />
        ) : (
          <Route path="/" component={Homepage} />
        )}
        <Route
          path="/explore/:category"
          component={Explore}
        />
      </Switch>
</BrowserRouter>

But, the router keeps only showing the AnonHomepage and/or the Homepage in that / route, never the /explore (or any other) route anymore. What am I doing wrong? How can I make it use the correct components instead of always showing the base route's components?


Solution

  • You can use the exact prop on the Route

    import { BrowserRouter, Switch, Route } from 'react-router-dom';
    
    ...
    
    <BrowserRouter>
          <Switch>
            {anon ? (
              <Route exact path="/" component={AnonHomepage} />
            ) : (
              <Route exact path="/" component={Homepage} />
            )}
            <Route
              path="/explore/:category"
              component={Explore}
            />
          </Switch>
    </BrowserRouter>