Home > Mobile >  How to pass id in Route React
How to pass id in Route React

Time:04-26

I want to build a page when from list of products I want to see product by ID. In my App file I have something like that:

<Route path={ROUTES.product} element={<Product id={1} />}> 

but I want to replace static id with the value that comes from the selected product. In my Product file I have redirection to page with product but I don't know how I can pass the ID.

onClick={() => { navigate(`/products/${product?.id}`)}}

Any help would be appreciated.

CodePudding user response:

onClick={ () => Navegar(id) }

function Navegar(id) {

navigate('/products/id)

}

CodePudding user response:

so you already have the id with this

navigate(`/products/${product?.id}`)

just in Product component you can access id with

 const { id } = useParams();

if you need to pass extra data you can try:

navigate(`/product/${product?.id}`, { state: { someExtradata }};

that you can access state in the component with :

 const { state } = useLocation();

CodePudding user response:

The code you've provided appears to pass the id value in the path. It seems your question more about getting the Product component to have the correct id prop passed to it.

Given: path is "/products/:id"

Options to access the id param:

  1. Use the useParams hook in Product to read the id route path param. This only works if Product is a function component.

    import { useParams } from 'react-router-dom';
    
    ...
    
    const { id } = useParams();
    

    ...

    <Route path={ROUTES.product} element={<Product />} />
    
  2. Use a wrapper component to use the useParams hook and inject the id value as a prop. This is useful if Product is not a function component.

    import { useParams } from 'react-router-dom';
    
    const ProductWrapper = () = {
      const { id } = useParams();
      return <Product id={id} />
    };
    

    ...

    <Route path={ROUTES.product} element={<ProductWrapper />} /> 
    
  3. Create a custom withRouter Higher Order Component to use the useParams hook and inject a params prop.

    import { useParams, ...other hooks... } from 'react-router-dom';
    
    const withRouter = Component => props => {
      const params = useParams();
      ... other hooks...
      return (
        <Component
          {...props}
          params={params}
          ... other hooks ...
        />
      );
    };
    

    ...

    Wrap Product with withRouter HOC and access id param from props.params

    props.params.id // or this.props.params
    
    ...
    
    export default withRouter(Product);    
    

    ...

    <Route path={ROUTES.product} element={<Product />} />
    
  • Related