Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide Nav bar in some react components

I am trying to make a login flow using react. Routes are working as expected. But when I try to introduce nav bar, it is visible on all routes. I want to show nav bar only on selected components (only on profile and home route).

Any suggestions would be appreciated.

This is the Routes.js:

export default class Routes extends Component {
  render() {
    return (
      <Switch>
        <Route
          exact
          path='/*/home'
          component={Home}
        />
        <Route
          exact
          path='/*/login'
          component={Login}
        />
        <Route
          exact
          path='/*/profile'
          component={Profile}
        />
        <Route
          exact
          path='/'
          component={Main}
        />
        <Route
          exact
          path='/*/'
          component={Org}
        />
      </Switch>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

This is the App.js:

<div className="App">
  <Nav />
  <Routes />
</div>
like image 482
Akashdeep Samantra Avatar asked Nov 01 '18 08:11

Akashdeep Samantra


People also ask

How hide navbar on specific page react?

To hide navbar in login page in React Router, we can put our nav bar inside the container with the authenticated routes. import React from "react"; const MyComponent = () => { //...

How do I hide the navbar on certain pages?

Go to your Navbar settings and find the navigation item you want to hide for a particular page. Click to edit and assign it a classname. You could assign it something like "hide-navigation-item."

How do I restrict navigation in react JS?

To restrict access to routes in React Router, we set the render prop to a function that renders the component we want according to the condition we're checking. import { Route, Redirect } from "react-router"; <Route exact path="/" render={() => (loggedIn ?


1 Answers

Your Nav component is being rendered in every view because it's located outside your views. There are a couple of options here:

  1. Move Nav into home & profile only. This would make sense if you wanted to keep your Routes component the same.
  2. Build a higher-order component for rendering a view withNav. This would be the best option if you need to render more than just home & profile with a Nav on top. Let's say you have a modal that needs to have the exact same Nav (for some reason), it may make sense to build an HOC
  3. Change your component tree to reflect the structure that you need. If only home & profile need the Nav, it may make sense to declare those two routes in a separate component.
like image 186
David Zhang Avatar answered Sep 24 '22 16:09

David Zhang