Home > Software engineering >  React Router Dom
React Router Dom

Time:11-30

My Navbar isn't showing when i start the app

this is the code

    <Router>
      <Routes> 
        <Route path='/' element={<Navbar/>,<Products/>
        <Route path='/product-view/:id' element={<Navbar/>,<ProductView/>}/>
      </Routes>
    </Router>

CodePudding user response:

My guess here is that you are trying to render multiple components. Valid JSX requires returning a single node element to render. Wrap each in a Fragment.

<Router>
  <Routes> 
    <Route
      path='/'
      element={(
        <>
          <Navbar />
          <Products />
        </>
      )}
    />
    <Route
      path='/product-view/:id'
      element={(
        <>
          <Navbar />
          <ProductView />
        </>
      )}
    />
  </Routes>
</Router>

If you are wanting to consistently render the Navbar on multiple routes then a more optimal solution is to create a layout wrapper component that renders nested Route components into an Outlet.

const ProductLayout = () => (
  <>
   <Navbar />
   <Outlet />
 </>
);

...

<Router>
  <Routes> 
    <Route path="/" element={<Layout />} >
      <Route index element={<Products />} />
      <Route path='/product-view/:id' element={<ProductView />} />
    </Route>
  </Routes>
</Router>
  • Related