How to pass URL parameters to component with React Router?

Estimated read time 2 min read

In React Router, you can pass URL parameters to a component by defining a dynamic path parameter in the route and accessing the parameter through the useParams hook.

Here’s an example of how to pass URL parameters to a component with React Router:

import React from 'react';
import { useParams } from 'react-router-dom';

function MyComponent() {
  const { id } = useParams();

  return (
    <div>
      <h1>My Component</h1>
      <p>ID: {id}</p>
    </div>
  );
}

export default function App() {
  return (
    <Routes>
      <Route path="/my-component/:id" element={<MyComponent />} />
    </Routes>
  );
}

In this example, we’re defining a MyComponent that accesses the id URL parameter using the useParams hook. We’re then rendering the id parameter in a <p> element.

We’re defining a dynamic path parameter called id in the Route component. We’re using a colon (:) before the parameter name to indicate that it’s a dynamic parameter.

In App, we’re rendering the MyComponent component with the id parameter defined in the path. The id parameter will be passed to the MyComponent component through the useParams hook.

By defining dynamic path parameters in the Route component and using the useParams hook, you can easily pass URL parameters to a component with React Router.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply