How to pass parameters to components with React Router?

Estimated read time 2 min read

With React Router, you can pass parameters to components using URL parameters. URL parameters are defined in the route path and can be accessed as props in the component that is rendered for that route. Here’s how to do it:

  1. Define a route with URL parameters: Define a route with URL parameters in your app’s router configuration. For example:
import React from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/users/123">User 123</Link>
            </li>
            <li>
              <Link to="/users/456">User 456</Link>
            </li>
          </ul>
        </nav>

        <Switch>
          <Route path="/users/:id">
            <User />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

export default App;

In this example, we’ve defined a route with a URL parameter :id. The value of :id can be any string and will be passed to the User component as a prop.

  1. Access the URL parameter in the component: Access the URL parameter in the component that is rendered for that route. In our example, we’re rendering the User component for the /users/:id route. Here’s an example User component that accesses the URL parameter:
import React from 'react';
import { useParams } from 'react-router-dom';

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

  return <h1>User {id}</h1>;
}

export default User;

In this example, we’re using the useParams hook from react-router-dom to access the id parameter from the URL. We’re then using that value to render a heading with the user’s ID.

That’s it! You can now pass parameters to components with React Router using URL parameters. Note that you can pass multiple URL parameters in a single route path by separating them with slashes, and you can access them all in the component using useParams.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply