Home > Blockchain >  Multiple Routes ReactJS
Multiple Routes ReactJS

Time:10-26

Is it possible to have two Route element to be matched all the time? I gave my Navigation element rendered all the time, and nested elements are rendering, depending on further path. I would like my MobileNavigation element also be rendered all the time (well, while isMobile === true) together with Navigation, how can I achieve it?

function App() {
  const { isMobile } = useContext(UserContext)

  return (
    <div className="App">
      <Routes>
        <Route path='/' element={<Navigation />}>
          <Route index element={<Home />} />
          <Route path='auth' element={<Authentication />} />
          <Route path='shop' element={<Shop />} />
          <Route path='checkout' element={<Checkout />} />
          <Route path='shop/:slug' element={<FullItemPage />} />
          <Route path='favorite' element={<Favorite />} />
        </Route>
         // I've tried to put it here, but both variants have failed
         // <Route index element={isMobile ? <MobileNavigation />  : null} />
         // {isMobile ? <Route index element={<MobileNavigation />}  /> : null} 
      </Routes>
    </div>
  );
}

export default App;

CodePudding user response:

Create/modify the layout route that is rendering the Navigation component to also conditionally render the MobileNavigation component.

Example:

const Layout = () => {
  const { isMobile } = useContext(UserContext);

  return (
    <>
      <Navigation />
      <Outlet />
      {isMobile && <MobileNavigation />}
    </>
  );
};

function App() {
  return (
    <div className="App">
      <Routes>
        <Route path='/' element={<Layout />}>
          <Route index element={<Home />} />
          <Route path='auth' element={<Authentication />} />
          <Route path='shop' element={<Shop />} />
          <Route path='checkout' element={<Checkout />} />
          <Route path='shop/:slug' element={<FullItemPage />} />
          <Route path='favorite' element={<Favorite />} />
        </Route>
      </Routes>
    </div>
  );
}
  • Related