reactjsreact-routerreact-router-domreact-dom

Hide header on some pages in react-router-dom


Is there a way I can hide my page header for only some routes in React Router? My issue now is that my App component renders my Main component, which contains my BrowserRouter, and my Header is rendered in my App component, so I have no way of rendering the header based on the route path.

Here's some code:

App.js

import React from 'react';
import {BrowserRouter} from 'react-router-dom';
import Main from './Main';
import Header from './Header';
import Footer from './Footer';

const App = () => (
    <BrowserRouter>
        <Header/>
        <Main/>
        <Footer/>
    </BrowserRouter>
);

export default App;

Main.js

import React from 'react';
import {Route, Switch} from 'react-router-dom';
import Home from './Home';
import Login from './Login';

const Main = () => (
    <main>
        <Switch>
            <Route exact path='/' component={Home}/>
            <Route exact path='/login' component={Login}/>
        </Switch>
    </main>
);

export default Main;

In this application, I would like to hide the header and footer on the login page.


Solution

  • I ended up using Redux. This was the best option because I have over twenty pages (only 3 shown in code below) on all of which the visibility of the header/footer vary. I created one reducer for the header and one for the footer. Here was my solution:

    import ...
    
    class App extends React.Component {
        render() {
            return (
                <BrowserRouter>
                    {this.props.header ? <Header/> : ''}
                    <Switch>
                        <Route exact path='/' component={Home}/>
                        <Route exact path='/login' component={Login}/>
                        <Route exact path='/signup' component={Signup}/>
                    </Switch>
                    {this.props.footer ? <Footer/> : ''}
                </BrowserRouter>
            );
        }
    }
    
    const mapStateToProps = state => state;
    export default connect(mapStateToProps)(App);