New to React. I have a React component Navbar.js that will display in 3 pages : Landing, Login and Home but with different tabs in each page.

For example, it will display a login button tab in the landing but will hide in login page and in the home page it will display a search box and logout button.

I tried to hide the menu icon when going from the landing page to the login page by testing on the URL:

const opendrawer = (
      <IconButton
        className={classes.menuButton}
        color="inherit"
        aria-label="Open drawer"
      >
        <MenuIcon />
      </IconButton>
    );
 return (
      <div className={classes.root}>
        <AppBar position="static">
          <Toolbar>

{window.location.href.includes("/login") ? null : opendrawer}


            </div>
          </Toolbar>
        </AppBar>

After trying this the menu icon did hide but only when I refresh the page manually.

1 Answers

0
jorgen g On

You can use props to this, create a constant informing which elements you want to render this specific icon. I did something similar on my application, I wanted to render a bottom bar only in some pages:

App.js

const tasks = {
  task1: {
    bottombar: true,
    // more features you want to turn on or off
  },
  task2: {
    bottombar: false,
  },

// Route is the React Component used for routing,
// Canvas is the component I use to draw the main pages of my app
// the {...props} passes all the feature configuration I previously did
// the module segment I pass the module to render, in this case those two tasks
<Route path="(/task1)" render={(props) => <Canvas {...props} module={tasks.task1} />} />
<Route path="(/task2)" render={(props) => <Canvas {...props} module={tasks.task2} />} />

Canvas.js

render() {
  return (
     // it will check if the props I passed here is true and render the component 
     // or the feature I want, If it is false, it will render nothing, undefined
     {this.props.module.bottombar ? <BottomBar {...this.props} selectedElement={this.state.selectedElement} /> : undefined}
  );
}