'How to set dynamic route with query params in react-router-dom
I need to set a dynamic route with query params -> http://localhost:3000/reset-password/?id=2
<Route path="/reset-password/?id=:id" component={ResetPassword} />
But this isn't working and it's showing as page not found. Please help on this.
Solution 1:[1]
<Route path="/reset-password/:id" component={ResetPassword} />
Url to visit: http://localhost:3000/reset-password/2
Solution 2:[2]
- No need for the
?id=:id, thats part of react-router - You probably need the
exactkeyword;
<Route exact path={"/reset-password/:id"} component={ResetPassword} />
Then, in the ResetPassword component, use the following prop to get the :id;
this.props.match.params.id
React : difference between <Route exact path="/" /> and <Route path="/" />
Solution 3:[3]
Get rid of the query string.
<Route path="/reset-password/:id" component={ResetPassword} />
Solution 4:[4]
Found a solution here for query strings, but i'd recommend using params and useParams() hook which don't need any setup and has the same usability as shown below
function useQuery() {
return new URLSearchParams(useLocation().search);
}
const { id } = useQuery();
Solution 5:[5]
<Route path="/reset-password" exact render={(props) => <ResetPassword {...props} />} />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TokaLazy |
| Solution 2 | 0stone0 |
| Solution 3 | aolivera |
| Solution 4 | Kakiz |
| Solution 5 | Darda |
