DEV Community

Charles 🛰
Charles 🛰

Posted on

Dynamic routes in react-router v6

Hey I found my self with a problem of not knowing how to do dynamic routes in react router v6 so here it is a short tutorial

In the file where you have your routes let's make a new dynamic routes such like this

App.tsx

    <BrowserRouter>
      <Routes>
        <Route index element={<Main/>}/>
        <Route path='/main' element={<Home />}/>
        <Route path='/main/:id' element={<ProductPage/>}/>
      </Routes>
      </BrowserRouter>
Enter fullscreen mode Exit fullscreen mode

You will notice that the dynamic route is the one with the :id, once we got this we should go to the component page which in this case is ProductPage

ProductPage.tsx

import { useParams } from 'react-router-dom';
import React, { useContext } from 'react';
import shopContext from '../context/shopContext';

const ProductPage = () => {
    const state = useContext(shopContext)
    const { id } = useParams();
    const product = state.list.find((p: any) => p.id === id)

    return(
        <div>
            <h1 style={{color: 'white'}}>{product.title}</h1>

        </div>
    )
}

export default ProductPage;
Enter fullscreen mode Exit fullscreen mode

Here you will see a lot but the main thing here is the following

 const { id } = useParams();
    const product = state.list.find((p: any) => p.id === id)
Enter fullscreen mode Exit fullscreen mode

Here is where with useParams we know the url id and then on the product constant we compare it with the data from the api or mock data.

Once we got that from the product constant we can access to the data from our api like so

return(
        <div>
            <h1 style={{color: 'white'}}>{product.title}</h1>

        </div>
Enter fullscreen mode Exit fullscreen mode

And now how to pass the data and navigate to the right page? Let's see

 <Link to={`/main/${data.id}`}>
 </Link>
Enter fullscreen mode Exit fullscreen mode

With the above we pass the id of the product when we are map all the data, so depends on what product do we click it will pass the id of the right product.

Hope someone found it helpful.

Lautaro

Top comments (0)