Route parameters are a powerful feature in React Router that allow you to create dynamic routes in your application. These parameters can be used to capture specific values from the URL and pass them as props to your components. This is particularly useful for building applications where you need to handle dynamic data, like displaying a user’s profile based on their unique ID or showing a specific product based on its ID.
1. What Are Route Parameters?
Route parameters are placeholders in the route path that can capture specific values from the URL. They are often used to display data that changes dynamically based on the URL, such as a user’s ID, product ID, or any other variable part of the URL.
2. Defining Route Parameters
In React Router, you define a route with parameters by adding a colon (:
) before the parameter name in the URL path.
Example: Defining a Route with Parameters
<Route path="/user/:id" component={UserProfile} />
Here, :id
is a route parameter. When a user navigates to /user/123
, the parameter id
will capture the value 123
.
3. Accessing Route Parameters
Once the route parameter is defined, you can access it inside your component using the match
object, which is automatically passed to your component by React Router.
Example: Accessing Route Parameters
import React from 'react';
function UserProfile({ match }) {
const { id } = match.params; // Accessing the 'id' route parameter
return <h2>User Profile for ID: {id}</h2>;
}
In this example:
match.params
contains the route parameters defined in the URL.match.params.id
retrieves the value of theid
parameter.
4. Using Route Parameters in URL
To demonstrate how route parameters work, let’s set up a few example routes in your application.
Example: Route with Parameter
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function UserProfile({ match }) {
return <h2>User ID: {match.params.id}</h2>;
}
function App() {
return (
<Router>
<Switch>
<Route path="/user/:id" component={UserProfile} />
</Switch>
</Router>
);
}
export default App;
In this example:
- The route
/user/:id
captures theid
parameter. - When you visit
/user/1
, theUserProfile
component will display “User ID: 1.”
5. Optional Route Parameters
React Router also supports optional parameters, which are not required to match the route. You can define optional parameters by adding a question mark (?
) to the parameter name.
Example: Optional Route Parameter
<Route path="/user/:id?" component={UserProfile} />
In this example, the id
parameter is optional. You can now visit both /user/123
and /user
without the application throwing an error.
6. Programmatic Navigation with Parameters
You can navigate programmatically to a route with parameters using React Router’s history.push()
or useHistory
hook.
Example: Programmatic Navigation
import React from 'react';
import { useHistory } from 'react-router-dom';
function RedirectButton() {
const history = useHistory();
const redirectToUser = (id) => {
history.push(`/user/${id}`); // Navigate to the route with the ID parameter
};
return (
<div>
<button onClick={() => redirectToUser(123)}>Go to User 123</button>
</div>
);
}
In this example, clicking the button will navigate to /user/123
programmatically.
7. Query Parameters vs. Route Parameters
It’s important to differentiate between query parameters and route parameters.
- Route parameters are part of the path, such as
/user/:id
. - Query parameters are part of the URL after a
?
, such as/user?id=123
.
Example of Query Parameters
// URL: /user?id=123
function UserProfile({ location }) {
const searchParams = new URLSearchParams(location.search);
const id = searchParams.get('id'); // Accessing query parameter 'id'
return <h2>User ID: {id}</h2>;
}