Ali Lotfi
Ali Lotfi

Reputation: 135

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

Upvotes: 2

Views: 21218

Answers (3)

Drew Reese
Drew Reese

Reputation: 203322

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"

  ...
}

Upvotes: 6

Usama
Usama

Reputation: 1235

You can use navigate

import { useNavigate } from "react-router-dom";

let navigate = useNavigate();

 navigate({
  pathname: '/callback',
  search: `?code=${data}`,
});

Then use useLocation to get the code from url.

const search = useLocation().search;
const id = new URLSearchParams(search).get("code");

Helpful link

Upvotes: 1

Ajay Gupta
Ajay Gupta

Reputation: 841

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>
    );
  }
}

Upvotes: 2

Related Questions