Q1. How do you pass parameters in React Router?
You define a route with a parameter using a colon:
Then in the
<Route path="/user/:id" element={<User />} />.Then in the
User component, you can access the parameter using the useParams hook.Q2. What is the useParams hook?
For example, if the URL is
It's used to access route parameters in a component.
useParams returns an object of key/value pairs of URL parameters.For example, if the URL is
/user/42, useParams() returns { id: '42' }.It's used to access route parameters in a component.
Q3. How do you handle optional parameters?
You can define multiple routes or use a parameter with a suffix.
In v6, you can use a wildcard or define a route with optional segment using
In v6, you can use a wildcard or define a route with optional segment using
? but it's not directly supported; instead, you can use different paths or read query parameters.Q4. How do you access query parameters (search string)?
Use the
Example:
useLocation hook to get the location object, then parse location.search with URLSearchParams.Example:
const query = new URLSearchParams(useLocation().search);
const name = query.get('name');
Q5. Can you have multiple parameters in a route?
Yes, you can have multiple parameters:
Then
/category/:catId/product/:prodId.Then
useParams gives { catId: '...', prodId: '...' }.