bp123
bp123

Reputation: 3427

Hide NavBar on certain routes - React Router V4

I'm using react-router v4 and I'd like to hide the NavBar on certain routes. How can I hide the NavBar on the login page? I've tried a few different solutions but none seems to work. Some insight would be appreciated.

const App = appProps => (
  <Router>
    <ScrollToTop>
      <Container fluid>
        <NavBar {...appProps} />
          <Switch>
            <Route name="landing" path="/landing" component={LandingPage} {...appProps} />
            <Route name="login" path="/login" component={LoginPage} />
          </Switch>
      </Container>
    </ScrollToTop>
  </Router>
);

Upvotes: 2

Views: 3041

Answers (1)

You should have a layout component that renders the required components depending on the route.

const AppLayout = (props) => {
    return (
        <ScrollToTop>
            <Container fluid>
                {props.navBar ? React.createElement(props.navBar) : null}
                {props.children}
            </Container>
        </ScrollToTop>
    );
};

Then create the following route component that passes down its props the the layout:

const AppRoute = ({ component, ...routeProps }) => {
    return (
        <Route {...routeProps} render={(props) => {
            return (
                <AppLayout { ...props} {...routeProps}>
                    {React.createElement(component, props)}
                </AppLayout>
            );
        }} />
    );
};

Finally, update your App component so it looks like this:

const App = appProps => (
    <Router>
        <Switch>
            <AppRoute name="landing" path="/landing" navBar={NavBar} component={LandingPage} {...appProps} />
            <AppRoute name="login" path="/login" component={LoginPage} />
        </Switch>
    </Router>
);

Upvotes: 2

Related Questions