5

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.

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
Ajit Kumar
  • 367
  • 1
  • 10
  • 35

1 Answers1

5

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.

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87