DEV Community

Charles 🛰
Charles 🛰

Posted on

5 1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more