Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dynamic routing in React router v6

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

like image 312
Ali Lotfi Avatar asked Dec 29 '25 16:12

Ali Lotfi


2 Answers

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"

  ...
}
like image 71
Drew Reese Avatar answered Jan 01 '26 07:01

Drew Reese


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>
    );
  }
}
like image 33
Ajay Gupta Avatar answered Jan 01 '26 08:01

Ajay Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!