'React-router-dom v6 params
How do I create a route in react using react-router-dom v6?
Currently I'm trying:
<Route path="/registration:id" element={<Registration />} />
With a url of "http://localhost:3000/registration?code=testCode", I get the error:
No routes matched location "/registration?code=testCode
I've tried manipulating the route path in many different ways and the only way it works is if the path doesn't have the query part ":id".
Is this the new syntax for v6 or am I doing something wrong?
Solution 1:[1]
React-router-dom generally only deals with the path part of the URL and not the querystring, and in RRDv6 there exists a useSearchParams hook you can use to access the querystring params. You won't specify any path match params though as this should be for matching the path part of the URL.
Given:
- path
"/registration?code=testCode"
<Route path="/registration" element={<Registration />} />
Example:
const [searchParams] = useSearchParams();
const code = searchParams.get('code'); // "testCode"
Solution 2:[2]
Put "/" after registration
<Route path="/registration/:id" element={<Registration />} />
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 | Drew Reese |
Solution 2 | Tobias S. |