Lesson #13 of 13 in Getting Started with React

Route Parameters with React Router

The React Router can handle route parameters that we see in the URL. Route parameters are parts of the URL that will change based on the object we want to display. For example, if we wanted to view information on a user named "chris", we would visit the path /users/chris. However, if we want to view information on a user named "kapehe", we would visit /users/kapehe. That last part of the URL is the parameter.

With react-router-dom, we designate a dynamic portion of the URL to be matched by putting a colon (:) before it.

For example, if we wanted a users route that displayed a user based on their username in the URL, we would write a route with path="/users/:username":

javascript
import {
  BrowserRouter as Router,
  Switch,
  Route
} from "react-router-dom";

export default function App() {
  return (
    <Router>
      <Switch>

        {/* all routes that look like /users/chris will be handled by the UserProfile component */}
        <Route path="/users/:username" component={UserProfile} />

      </Switch>
    </Router>
  );
}

Notice that we have :username there. This is a dynamic parameter. It will match any string of characters and it will be passed to the component.

Now that we have passed our route parameters to the component, we can access them in the component using the useParams hook.

javascript
// the UserProfile component
import { useParams } from "react-router-dom";

export default function UserProfile() {
  // get the username from route params
  const { username } = useParams();

  // now we have access to the username that came from the URL
  return <div>hi there {username}</div>; 
}

You can pull any route parameters that you created with the : syntax. If we wanted a route that had a course and a lesson, we could write:

javascript
// create the route
<Route path="/:course/:lesson" component={Lesson} />

// access the route parameters in the component
const { course, lesson } = useParams();

To create links to these dynamic routes, we would probably have an array that we looped over. If we had a list of users that we wanted to show a list of, we could write:

javascript
import { Link } from "react-router-dom";

// we have a list of users
const users = [
  { name: "Chris", username: "chris" },
  { name: "Kapehe", username: "kapehe" },
];

export default function UserList() {
  // loop over users them with jsx
  return (
    <div>
      {users.map((user) => (
        <Link to={`/users/${user.username}`}>{user.name}</Link>
      ))}
    </div>
  );
}
Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)