Home > Back-end >  Hide Header and Footer for specific Components in React JS
Hide Header and Footer for specific Components in React JS

Time:10-08

I am working on react js project. I need to hide the header and footer for some specific components. I tried it with the following code snippet in the header component.

class Navbar extends Component {
state = {}
render() {
    const {user} = this.props;
    if (window.location.pathname === "/sign-in" || window.location.pathname === "/sign-up" || window.location.pathname === "/vehicles/reservation") return null;
    return (
        <header className="bg-gray-200 sticky z-50 h-20 md:h-auto top-0">...</header>);
    }
}

Since the render method is called only when there is a change, the above condition is not checked every time. How do I make a solution for this problem?

CodePudding user response:

You can pass a state variable as a props from parent component, for updating child component.

Parent componente:

state = {
    updateNavbar: false,
  }

//when is necessary update navbar:
this.setState(state => ({
      updateNavbar: !updateNavbar,
    }))

...
<Navbar updateNavbar={this.state.updateNavbar}>

CodePudding user response:

If you want React to interact with the URL, you usually use a router. react-router is the popular one.

  • Related