How to use path in react Router Route for the following format

Viewed 92

I need to use the following path in React Router

http://localhost:3000/testgroup/test/callback/?code=2d54b51d

I'm using the following code to declare the path but its not working. Any idea on how to use this? It works on callback/:code but my callback url comes in the above format from the source. Also, how do I extract the code from the url in react router. Please note, I'm using the older version as the current application is in the older version.

 <TestRoute
          
          // authenticated={true}
          path={`${userRoute}/test/callback/?code=:code`}
          component={CallBackHandler}
          history={history}
        />
1 Answers

react-router-dom only concerns itself with the path portion of a URL, the queryString isn't used for path matching.

  1. Remove the queryString from the route path.

    <TestRoute
      // authenticated
      path={`${userRoute}/test/callback/`}
      component={CallBackHandler}
      history={history}
    />
    
  2. Read the queryString params from the location object in the component once it is mounted. It's useful to create a custom hook to access the location.search and return a memoized URLSearchParams object.

    const { useLocation } from 'react-router-dom';
    
    const useSearchParams = () => {
      const { search } = useLocation();
      return React.useMemo(() => new URLSearchParams(search), [search]);
    };
    
    const CallBackHandler = props => {
      const searchParams = useSearchParams();
      const code = searchParams.get("code");
    
      ...
    };
    
Related