I have a callback link https://localhost:3000/callback?code=1234
How do you provide a dynamic route for the code? You are not allowed to replace the "?" with a "/".
So I would like to have something like this:
<Route path="callback?{dynamic data here}" element={Component } />
I'm using react-router@6
The queryString part of a URL isn't considered when using the path part of a URL to match and render routes. The route should specify only the path that it needs to match, and the routed component then needs to read the queryString parameters it needs.
Example:
<Route path="/callback" element={<Component />} />
The dynamic part is in how you link/navigate to the "/callback" route.
Using a Link component
<Link
to={{
pathname: "/callback",
search: `?code=${code}`, // inject code value into template
}}
>
Code
</Link>
Using the Navigate component
<Navigate
to={{
pathname: "/callback",
search: `?code=${code}`, // inject code value into template
}}
/>
Using navigate function
navigate({
pathname: "/callback",
search: `?code=${code}`, // inject code value into template
});
The Component should use the useSearchParams hooks to access the queryString parameters.
For URL "/callback?code=1234"
const Component = () => {
const [searchParams] = useSearchParams();
const code = searchParams.get("code"); // "1234"
...
}
You need to use link dynamically.
<BrowserRouter>
/* Links */
{listofcodes.map(x=> (<Link to={'callback/' + x.code} />)}
/* Component */
<Route path="callback/:code" component={callback} />
</BrowserRouter>
class callbackextends Component {
render() {
return (
<div>
{this.props.match.params.code}
</div>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With