0

I have a component called Product which gets prop called product which is an object containing attributes such as id, slug, name etc.

function Product({ product }) {
    const productLink = `/products/${product.slug}`;
    return (
       <Link to={productLink} ></Link>
    )
}

Here, I am linking to ProductScreen component using the slug field. This is the Route i have <Route path='/products/:slug' element={<ProductScreen />} />

I have ProductScreen component like this

function ProductScreen() {
    const { slug } = useParams();
    return (...)
}

In ProductScreen, i want to get id also because i want to make an axios call like {{baseUrl}}/products/id but all i have is slug here.

In Link component, i know i can pass id as a state prop like <Link to={productLink} state={{id:id}} ></Link> but this is not the ideal solution i feel. Is there any way i can pass id from Link in Product to ProductScreen.

Srivatsa
  • 94
  • 1
  • 8
  • If you want anything is passed via a route transition to be "hidden" then it can't be part of the URL, e.g. not in the path as a path param and not in the search string as a query param. You are left with passing it in route state. The alternative is to stash it in *some* global app state or localStorage, etc. – Drew Reese May 30 '23 at 16:43
  • can you explain what do you mean by global app ? – Srivatsa May 30 '23 at 17:02
  • Global app state -> some centralized app state accessible by the entire app. It could be provided via a React Context provider, it could be a Redux state, etc. – Drew Reese May 30 '23 at 17:03

0 Answers0