React JS route parameters and query strings
In React Router, route parameters and query strings are two ways to pass dynamic information through URLs. Here’s how you can work with both:
Route Parameters
Route Parameters are used to capture dynamic segments of a URL. They are part of the path and are defined using a colon (:
) followed by a parameter name in the route definition.
Example
Let's say you have a route for user profiles where each user has a unique ID. You can define a route with a parameter for the user ID:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function UserProfile({ match }) {
return <h2>User Profile for user with ID: {match.params.id}</h2>;
}
function App() {
return (
<Router>
<div>
<nav>
<ul>
<li><Link to="/users/1">User 1</Link></li>
<li><Link to="/users/2">User 2</Link></li>
</ul>
</nav>
<Switch>
<Route path="/users/:id" component={UserProfile} />
</Switch>
</div>
</Router>
);
}
Accessing Route Parameters
In the UserProfile
component:
match.params.id
contains the value of theid
parameter from the URL.
Query Strings
Query Strings are a part of the URL that comes after the ?
character and are used to pass optional parameters. They are typically used for filtering, sorting, or pagination.
Example
Let’s say you want to filter a list of items based on a query parameter:
import { BrowserRouter as Router, Route, Switch, useLocation } from 'react-router-dom';
function Items() {
const location = useLocation();
const query = new URLSearchParams(location.search);
const filter = query.get('filter') || 'all';
return <h2>Items List with filter: {filter}</h2>;
}
function App() {
return (
<Router>
<div>
<nav>
<ul>
<li><Link to="/items?filter=all">All Items</Link></li>
<li><Link to="/items?filter=popular">Popular Items</Link></li>
<li><Link to="/items?filter=recent">Recent Items</Link></li>
</ul>
</nav>
<Switch>
<Route path="/items" component={Items} />
</Switch>
</div>
</Router>
);
}
Accessing Query Strings
In the Items
component:
useLocation
is a hook provided by React Router that returns the current location object.new URLSearchParams(location.search)
parses the query string from the URL.query.get('filter')
retrieves the value of thefilter
parameter.
Summary
Route Parameters: Define dynamic segments in your URL paths using
:paramName
in theRoute
path. Access them viamatch.params
in the component.Query Strings: Use URL parameters after the
?
character to pass optional data. Access them usinguseLocation
andURLSearchParams
to parse and retrieve query parameters.
Both techniques are useful for handling different types of dynamic data in your React Router setup.