首页 > 解决方案 > How to pass props to child component based on dynamic route

问题描述

I'm trying to make an ecommerce website with react and react-router-dom. I have different components: ProductsList, Product, Details (about single product).

I am using Context API in a separate file. My App.js file looks like this:

...imports
const products = useContext(ProductContext)

const App = () => {
   ...
   <Route path="/products/:id">
     <Details products={products} />
   </Route>
}

But I want to send details only about the product whose id matches the dynamic route id, not the whole array of products. But how do I extract that id? I know I can do it inside the Details.jsx file by using useParams(). But how do I do that from inside App.js?

I just noticed there's a similar quesiton. But I want my Details component in its own file and not inside App.

标签: reactjsreact-router-dom

解决方案


您可以尝试以下操作:-

...imports
const products = useContext(ProductContext)

const App = () => {
   ...
   <Route path="/products/:id" render={(props) => {
   const id = props.match.params.id;
   const productData = products.find(product => product.id === id);
     return <Details {...props} product={productData} />
   }}
   </Route>
}


推荐阅读