6

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.

2
  • 1
    If the framework doesn't support this directly, as an alternate approach you might put the logic within <PageOne> itself, grabbing the id value from the query string and conditionally displaying the target component internally. Commented Jan 12, 2022 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? Commented Jan 12, 2022 at 20:03

1 Answer 1

6

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 />} />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.