Why the fallback route always got triggered? Even though another route hit first

Viewed 82

Why user accesses #app/react/index

Both index and FallbackPage are triggered. Why?

    <Router basename={`<URL>#app/react}>
        <Switch history={history}>
            <div className={`layout`}
                <nav className="navbar navbar-expand-lg navbar-light bg-light">
                    .....
                </nav>
                <Route exact path='/index'>
                    <h1>Index</h1>
                    .....
                </Route>
                <Route path="/"
                    component={FallbackPage}/>
            </div>
        </Switch>
2 Answers

Please wrap Route with Switch directly.

<Router basename={`<URL>#app/react}>
    <div className={`layout`}
        <nav className="navbar navbar-expand-lg navbar-light bg-light">
                .....
        </nav>
        <Switch history={history}>
            <Route exact path='/index'>
                <h1>Index</h1>
                .....
            </Route>
            <Route path="/"
                component={FallbackPage}/>
        </Switch>
    </div>
</Router>

They are both hit since the Switch component is rendering a single div element. It's like being rendered by a normal router where all routes are matched and rendered inclusively.

You could move the nav and the layout div out of the Switch so it's wrapping and rendering only the Route components. Once you are rendering the routes directly into the Switch and ordering them from more specific to less specific paths, you won't need to specify the exact prop on the "/index" route.

<Router basename={'<URL>#app/react'}>
  <div className={'layout'}>
    <nav className="navbar navbar-expand-lg navbar-light bg-light">
      .....
    </nav>
    <Switch history={history}>
      <Route path='/index'>
        <h1>Index</h1>
        .....
      </Route>
      <Route path="/" component={FallbackPage}/>
    </Switch>
  </div>
</Router>
Related