skip to Main Content

In react-router V6, can you still use a parameter as React key?
In react-router V5, this could be achieved by writing:

<Switch>
  <Route path="products/:productId" render={({match}) => <ProductDetail key={match.params.productId}/>} />
</Switch>

Now, after the switch to react-router V6, how do you pass the key?

<Routes>
  <Route path="products/:productId" element={<ProductDetail key={?}/>}/>
</Routes>

Or is that no longer possible and should you add a wrapper container, which receives the productId param from useParams() and passes it on?

MyWrapper = () => {
  const { productId} = useParams();
  return <ProductDetail key={productId}/>;
}

2

Answers


  1. 
    const ProductDetailWrapper = () => {
     const { productId } = useParams();
     return <ProductDetail key={productId} />;
    };
    
    const App = () => {
     return (
       <Routes>
         <Route path="products/:productId" element={<ProductDetailWrapper />} />
       </Routes>
     );
    };
    
    Login or Signup to reply.
  2. You can create a HOD (Higher order component) which takes component as a prop, that would eliminate creating wrappers each time.

    Wrapper

    function MyWrapper = ({component:Component}) => {
        const { productId} = useParams();
        return <Component key={productId}/>;
    }
    

    Route

    <Routes>
      <Route path="products/:productId" element={<MyWrapper component={ProductDetail}/>} />
      <Route path="products2/:productId2" element={<MyWrapper component={ProductDetail2}/>} />
    </Routes>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search