Skip to content
Advertisement

Render specific react component based on the URL

App.js

function App() {
  <div className="App">
    <Router>
      <Switch>
        <Route exact path="/home" component={Home} />
        <Route exact path="/search" component={Home} />
      </Switch>
    </Router>
  </div>;
}

Home.js

function Home() {
    const location = useLocation();
    return (
        <div className="home">
            <Component1 />
            {location.pathname === "/home" && <Feed />}
            {location.pathname === "/search" && <Search />}
            <Component2 />
        </div>
    );
}

This works perfectly as I want to render the Feed or Search component depending on the URL.

But, I want to know is it okay to use location.pathname or is there any better alternative?

Advertisement

Answer

You could do something like:

App.js

function App() {
  return <div className="App">
    <Router>
      <Switch>
        <Route exact path="/home" component={() => <Home showFeed/>} />
        <Route exact path="/search" component={() => <Home showSearch/>} />
      </Switch>
    </Router>
  </div>;
}

Home.js

function Home(props) {
    const location = useLocation();
    return (
        <div className="home">
            <Component1 />
            {props.showFeed && <Feed />}
            {props.showSearch && <Search />}
            <Component2 />
        </div>
    );
}

This allows you to abstract away the Home component’s dependency on any routing mechanism, and simply allows you to control whether certain elements appear or not from outside this component.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement