Search code examples
reactjsreact-router-dom

How to create a route with get parameter in v6?


I have some routes that besides needing two different ids, some of them need to be forwarded as get parameter, how to do this in the current version of React Router Dom v6?

PATHS:

path='/shorts/:userShortId?&ab_channel=*'
path='/watch?v=*&ab_channel=*'

CODE:

export default function App() {
  return (
    <BrowserRouter basename='/'>
      <GlobalStyle />

      <Routes>
        <Route path='/' element={<HomePage />} />
        <Route path='/login' element={<HomePage />} />
        <Route
          path='/shorts/:userShortId?&ab_channel=*'
          element={<HomePage />}
        />
        <Route path='/watch?v=*&ab_channel=*' element={<HomePage />} />
        <Route path='/feed'>
          <Route path='subscriptions' element={<HomePage />} />
          <Route path='library' element={<HomePage />} />
        </Route>
        <Route path='/channel/:userChannelId' element={<HomePage />}>
          <Route path='videos' element={<HomePage />} />
          <Route path='playlists' element={<HomePage />} />
          <Route path='community' element={<HomePage />} />
          <Route path='channels' element={<HomePage />} />
          <Route path='about' element={<HomePage />} />
        </Route>
        <Route path='*' element={<NotFoundPage />} />
      </Routes>
    </BrowserRouter>
  );
}

Solution

  • From the tests I've been doing and by looking at the docs example, It seems that you don't need to define the query parameters in the route definition. You only need the path and path variables (:something). Then, inside of the component you can make use of react router useSearchParams hooks to retrieve the parameters from the URL.

    export default function App() {
      return (
        <BrowserRouter basename="/">
          <Routes>
            <Route path="/" element={<h1>Home</h1>} />
            <Route path="/login" element={<h1>Login</h1>} />
            <Route path="/shorts/:userShortId" element={<Shorts />} />
            <Route path="/watch" element={<h1>watch</h1>} />
            ...
          </Routes>
        </BrowserRouter>
      );
    }

    And for instance, in the Shorts component you could have

    function Shorts() {
      const [searchParams] = useSearchParams();
    
      useEffect(() => {
        const paramsAsObject = Object.fromEntries([...searchParams]);
    
        console.log(paramsAsObject);
      }, [searchParams]);
    
      return <h1>shorts</h1>;
    }