Ajit Kumar
Ajit Kumar

Reputation: 417

Show Sidebar Navigation only at Home using React Router Dom

I made a Sidebar with navigation to 'home' and 'search' pages. But, what I want is that, I only need to show the Sidebar only on the 'home' page but not on the 'search' page. Here is what I have now:
App.js:

import React from "react";
import "./App.css";

import SideBar from "./components/SideBar";
import Home from "./screens/Home";
import Search from "./screens/Search";

import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

function App() {    
  return (
    <div className="app">
      <Router>
    <Switch>
      <SideBar />
      <Route exact path="/home">
        <Home />
      </Route>
    </Switch>

    <Switch>
      <Route exact path="/search">
        <Search />
      </Route>
    </Switch>
  </Router>
    </div>
  );
}

export default App;

But, it shows the Sidebar on both the pages.

Edit:

I don't want the sidebar to re-render when the route changes. In the Sidebar there are links to 'Home' and 'Search' pages. I only want those pages to render and re-render.

Upvotes: 5

Views: 1742

Answers (1)

Ajeet Shah
Ajeet Shah

Reputation: 19863

Note that all children of a <Switch> should be <Route> or <Redirect> elements. See related post. And, if you want to show <SideBar /> component only at <Home />, you can simply keep it inside the "/home" Route:

export default function App() {
  return (
    <div className="app">
      <Router>
        <Switch>
          <Route exact path="/home"> {/* Here */}
            <SideBar />
            <Home />
          </Route>
          <Route exact path="/search">
            <Search />
          </Route>
          <Route exact path="/foo">
            <Foo />
          </Route>
        </Switch>
      </Router>
    </div>
  )
}

Here is a demo.

PS: You should have only one Router in your app, or it will soon become an issue due to two React-Router-Contexts available in your app.

Upvotes: 5

Related Questions