How passing props to component (Dynamic Routing)

Viewed 34

Please tell me how I can passing props to component (Card) in dynamic routing. I get array from JSON and put it to Redux. Example JSON:

{
    "product": [
        {
            "id": 1,
            "image": "/assets/images/products/27672/1.jpg",
            "name": "Product 1",
            "price": "0.20",
            "category": 2
        },
        {
            "id": 2,
            "image": "/assets/images/products/27672/2.jpg",
            "name": "Product 2",
            "price": "0.1",
            "category": 3
        }
]
}

App component:

<div className="App">
  <Header />
  <Routes>
    <Route path='/' element={<Home />} />
    <Route path='/product/:id' element={<Card />} />
  </Routes>
  <Footer />
</div>

Link on product in Home component. Clicking on the link should take to product page. Id product from JSON.

<div className="catalog_block">
   <Link to={'product/' + id}>
     <img src={image} />
    </Link>
</div>
1 Answers

You pass props to Card like you would any other React component:

<Route path='/product/:id' element={<Card /* pass props here */ />} />

But what I really think you are asking for is how to use the id route path parameter to fetch a specific element from the product array. For this the Card component should use the useParams hook to access the id path parameter and then find the matching element from the product array.

Example:

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

const Card = () => {
  const { id } = useParams();
  const specificProduct = product.find(el => String(el.id) === id);

  ..

  if (!product) {
    // render no matching product JSX
  }

  return (
    // matching product JSX
  );
};

Alternatively you can pass the specific product in route state and access via the useLocation hook via location.state.

Example:

<Link
  to={'product/' + id}
  state={{ product: specificProductBeingIterated }}
>
  <img src={image} />
</Link>

...

import { useLocation } from 'react-router-dom';

const Card = () => {
  const { state } = uselocation();
  const { product } = state || {};

  ..

  if (!product) {
    // render no matching product JSX
  }

  return (
    // matching product JSX
  );
};
Related