Den Pat
Den Pat

Reputation: 1284

React Router V6 change component based on query string

I tried several thing to match the query string and show component according to that but no luck, my code:

  <Route path="/wp-admin/admin.php" element={<PageOne />} >
        <Route path="/wp-admin/admin.php/?id=two" element={<PageTwo />} />
        <Route path="/wp-admin/admin.php/?id=three" element={<PageThree />} />
  </Route>

I want to show component PageTwo and PageThree according to query string but it's not working, I tried using :id in parent Route but it's not working, I think I am missing something basic here.

Upvotes: 6

Views: 3929

Answers (1)

Drew Reese
Drew Reese

Reputation: 203466

react-router-dom only uses the path portion of a URL for route matching, the queryString is ignored.

What you can do though is create a wrapper component of sorts that reads from the queryString and returns the appropriate component to render.

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

const adminPages = {
  one: PageOne,
  two: PageTwo,
  three: PageThree,
};

const AdminPage = (props) => {
  const [searchParams, setSearchParams] = useSearchParams();

  const pageId = searchParams.get("id");

  const Page = adminPages[pageId] || adminPages["one"];
  return <Page {...props} />;
};

...

<Route path="/wp-admin/admin.php" element={<AdminPage />} />

Upvotes: 6

Related Questions