简体   繁体   中英

ReactJS hide header on invalid page(404)

I've recently started learning React and I've been trying to figure out how I would go about hiding my header when the user is trying to route to an invalid page/path. The only way I can think of is to manually add to each of my components and remove the from my App.js. For now I'm simply redirecting them to the home page. Below are my App and Root JS files. Before I had <Redirect to="/" /> , I used <Route component={invalidPage}/> to link to an InvalidPage component, but couldn't figure out a way to hide the header.

//App.js
class App extends React.Component {
    render(){
        return(
            <Router>
                <Root>  
                    <Switch>
                        <Route exact path={"/"} component={Home}/>
                        <Route exact path={"/user"} component={User}/>
                        <Route exact path={"/home"} component={Home}/>      
                        <Redirect to="/"/>
                    </Switch>
                </Root>
            </Router>
        );
    }
}

//Root.js
export class Root extends React.Component{
    render(){
        return(
            <div className="container">
                <div className="row">
                    <div className="col-xs-10 col-xs-offset-1">
                        <Header/>
                    </div>
                </div>
                <div className="row">
                    <div className="col-xs-10 col-xs-offset-1">
                        {this.props.children}
                    </div>
                </div>
            </div>
        );
    }
}

Use Higher Order Components. This approach should basically work. Tell me if you face difficulties.

//App.js
class App extends React.Component {
  render(){
    return(
      <Router>
          <Switch>
            <Route exact path={"/"} component={withRoot(Home)}/>
            <Route exact path={"/user"} component={withRoot(User)}/>
            <Route exact path={"/home"} component={withRoot(Home)}/>
            <Route component={invalidPage}/>
          </Switch>
      </Router>
    );
  }
}

const withRoot= (Component)=> <Root><Component/></Root>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM