React-router-dom v6. Navigate through products

React-router-dom v6. Navigate through products

Problem Description:

Hope someone can help me here.
Been trying different things but always end up just extending my routes.
What i want is to be able to navigate through products (its some kinda eshop)

So, when i am in 1st product with prod_G6kVw7pV6Oo2eD as product id

http://localhost:3000/combo/prod_G6kVw7pV6Oo2eD

I need to be able to go to the next product (go back and forth as I have 3 buttons called "Prev" and "Next"). 6 products in total.
That’s the array of product ids =

['prod_G6kVw7pV6Oo2eD', 'prod_RyWOwmPkL9lnEa', 'prod_ypbroE9QBno8n4', 'prod_Kvg9l61rEm51bB', 'prod_NqKE50NEPBwdgB', 'prod_kpnNwA1P8awmXB']

Once i reach the last product (prod_kpnNwA1P8awmXB) i need to go the first product.

In other words – just need to change product_id – last element of the route.

I think there is a good solution for this cos its a very common case. But I am unable to find.

Thanks!

Solution – 1

const comboproductsids = [
  'prod_G6kVw7pV6Oo2eD',
  'prod_RyWOwmPkL9lnEa',
  'prod_ypbroE9QBno8n4',
  'prod_Kvg9l61rEm51bB',
  'prod_NqKE50NEPBwdgB',
  'prod_kpnNwA1P8awmXB'
];

<Box onClick={() => navigate(`/${id[1]}/${comboproductsids[(index + 1) % comboproductsids.length]}`)} 

With the modulo, it will return 0 everytime you reache your array’s limit

Solution – 2

found solution!

<Box onClick={()=>navigate(`/${id[1]}/${comboproductsids[index+1]}`)} 

where const id = window.location.pathname.split("/"); const indexid = window.location.pathname.split("/")[2]; const index = comboproductsids.indexOf(indexid)

now just need to figure how to go back first product once i reach last product

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject