Ansul
Ansul

Reputation: 420

Prevent component render in specific page react-router

The 'navbar' and 'footer' gets rendered on every component's page. Is there an way to prevent rendering 'footer' in the 'user' component?

App.js

   <Router>
    <Route>
      <Navbar />
      <Switch>
        <Route path='/' exact component={Home} />
        <Route path='/About' exact component={About} />
      </Switch>
      <Footer />
    </Route>

    <Route>
      <Route path='/user' component={User} />
    </Route>

    <Route path='*' component={NotFound} />
  </Router>

Upvotes: 1

Views: 1515

Answers (1)

thelonglqd
thelonglqd

Reputation: 1862

Move the <Router> to index.js file like below to get access to props.location inside App.js

<Router>
  <App />
</Router>

Inside your App.js file:

const App = ({ location }) => {
  return (
    <Route>
      <Navbar />
      <Switch>
        <Route path='/' exact component={Home} />
        <Route path='/About' exact component={About} />
      </Switch>
      {location.pathname !== '/user' && <Footer /> }
    </Route>
    <Route>
      <Route path='/user' component={User} />
    </Route>

    <Route path='*' component={NotFound} />
  )
}

This solution works with react-router and react-router-dom v5+

Upvotes: 1

Related Questions