Search code examples
reactjsreact-routercomponentsrouter

React router conditional


I have multiple routers i import Nav component in index.js i need to show Nav only for About but i don't want to show Nav component for Topics. I do not want to import the Nav component inside Home and About, since I can have a lot of routers

const BasicExample = () => (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
        <li>
          <Link to="/topics">Topics</Link>
        </li>
      </ul>
      <Nav />
      <hr />

      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/topics" component={Topics} />
    </div>
  </Router>
);

You can also look at the complete code in codesandbox


Solution

  • You can create a HOC Layout that can take an additional props noNav to hide you nav:

    Component Layout:

    import React from "react";
    import { Link } from "react-router-dom";
    import Nav from "../components/Nav/Nav";
    
    const Layout = ({ children, noNav }) => (
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/topics">Topics</Link>
          </li>
        </ul>
        {noNav ? null : <Nav />}
        <hr />
    
        {children}
      </div>
    );
    
    export default Layout;
    

    index.js

    import React from "react";
    import { render } from "react-dom";
    import { BrowserRouter as Router, Route } from "react-router-dom";
    import About from "./components/About";
    import Home from "./components/Home";
    import Topics from "./components/Topics";
    import Layout from "./hoc/Layout";
    
    const BasicExample = () => (
      <Router>
        <div>
          <Route
            exact
            path="/"
            render={() => (
              <Layout>
                <Home />
              </Layout>
            )}
          />
          <Route
            path="/about"
            render={() => (
              <Layout>
                <About />
              </Layout>
            )}
          />
          <Route
            path="/topics"
            render={(props) => (
              <Layout noNav>
                <Topics {...props} />
              </Layout>
            )}
          />
        </div>
      </Router>
    );
    
    render(<BasicExample />, document.getElementById("root"));
    

    Demo: https://codesandbox.io/s/react-router-forked-k1ve2?file=/index.js:0-874