Search code examples
javascriptreactjsroutescomponentsreact-component

How to use {Switch, Route} in hierarchical components in React?


I have routes in App.js mainly Logout, Signin and Home.
Inside App.js :

return(
<>
<Switch>
      <Route exact path='/' component={Home} /> 
      <Route exact path='/signin' component={Signin} />
      <Route exact path='/logout' component={Logout} />
</Switch>
</>)

Also, I want Routes inside Home.js :

return( 
<>
<Navbar/>
<Switch>
      <Route exact path='/'>
        <LandingPage />
      </Route>
      <Route exact path='/settings'>
        <Settings username={username} />
      </Route>
</Switch>
</>
)

The LandingPage component is default for Home page, and Navbar is common in both LandingPage and Settings. LandingPage component is showing perfectly but when I click "settings" button from Navbar, the Settings component is not showing. Other Routes are working fine.
Inside Navbar I used NavLink:

<NavLink className="nav-link" to="/">
      HOME
</NavLink>
<NavLink className="nav-link" to="/settings">
      SETTINGS
</NavLink>

Why the Settings Component is not showing ???


Solution

  • <Route exact path='/' component={Home} /> 
    

    Because of the exact flag, anything that isn't precisely "/" will not match this. So when the url becomes "/settings", you stop rendering your Home component, which in turn means there's nothing trying to render a route at "/settings"

    The likely fix is to remove the exact, and also rearrange your components so this case comes after the sign in/sign out cases:

    <Switch>
      <Route exact path='/signin' component={Signin} />
      <Route exact path='/logout' component={Logout} />
      <Route path='/' component={Home} /> 
    </Switch>