5

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.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Den Pat
  • 1,118
  • 10
  • 17
  • 1
    If the framework doesn't support this directly, as an alternate approach you might put the logic within `` itself, grabbing the `id` value from the query string and conditionally displaying the target component internally. – David Jan 12 '22 at 19:58
  • @David Yes, that will work for normal situations but I am using Outlet here so I only need to change a portion of the page. any idea? – Den Pat Jan 12 '22 at 20:03

1 Answers1

3

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 />} />
Drew Reese
  • 165,259
  • 14
  • 153
  • 181