Home > Blockchain >  react-router-dom version 6 nested routes props not passing
react-router-dom version 6 nested routes props not passing

Time:02-12

I am unable to get the props from the nested routes, Products route has nested route which should print pc but I only get ssd,

Is this because I am using same component in the nested route ? or I am doing something wrong.

App.js

<BrowserRouter>
      <div className="app">
        <Header />
        <Routes>
          <Route index element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
          <Route path="products" element={<Products name="ssd"/>}>
            <Route path=":id" element={<Products ye="pc" />} />
          </Route>
          <Route path="*" element={<Err />}/>
        </Routes>
      </div>
    </BrowserRouter>

Products.jsx

import React from 'react'
import { useParams } from 'react-router-dom'

function Products(props) {
    const {id} = useParams(); 
    console.log(props);
  return (
    <div>
        <p>This product : {props.name} is in stock</p>
        <p>The id from the params is : {id}</p>
        <p>ye is : {props.ye}</p>
    </div>
  )
}

export default Products

Here is the screenshot of the console which show that only ssd is passed

enter image description here

CodePudding user response:

Products is missing rendering an Outlet for nested Routes to be rendered into.

import React from 'react'
import { Outlet, useParams } from 'react-router-dom'

function Products(props) {
  const { id } = useParams(); 
  console.log(props);
  return (
    <div>
      <p>This product : {props.name} is in stock</p>
      <p>The id from the params is : {id}</p>
      <p>ye is : {props.ye}</p>
      <Outlet /> // <-- nested routes render out here
    </div>
  )
}

Or alternatively if you don't want to nest Products components within other Products components, render the Outlet as the layout component and create an index route for the "ssd" route. The Route component renders an Outlet by default if no element prop is specified.

<Route path="/products">
  <Route index element={<Products name="ssd" />} />   // <-- "/products"
  <Route path=":id" element={<Products ye="pc" />} /> // <-- "/products/1234"
</Route>
  • Related