Search code examples
javascriptreactjsreact-routerreact-router-dom

How to access query parameters/search params in loader function in react router v6


I have a route configured like this:

const router = createBrowserRouter([
  {
    path: "/",
    element: <Layout />,
    children: [
      { index: true, element: <Home /> },
      { path: "contacts", element: <Contact /> },
      { path: "info/:link", element: <FooterLinks /> },
      { path: "faq", element: <FAQs /> },
      {
        path: "search",
        element: <SearchResults />,
        loader: async ({ params }) => {
          // NEED ACCESS TO QUERY PARAMETERS HERE
        },
      },
      {
        path: "disease/:id",
        element: <DiseaseDisplay />,
        loader: async ({ params }) => {
          ...
        },
      },
    ],
  },
]);

Is there any way to access the query parameters in the route in the loader function? For example if the route is "localhost:3000/search?searchTerm=aaa", how can I access the value of searchTerm in the loader function?


Solution

  • The Route loader is passed only the Request object and the route's path parameters, e.g. { params, request }. If you want to access the URL search string you can access it from the request.url value.

    Example:

    loader: async ({ params, request }) => {
      const [,searchParams] = request.url.split("?");
      const searchTerm = new URLSearchParams(searchParams).get("searchTerm");
    
      ...
    }
    

    or

    loader: async ({ params, request }) => {
      const searchParams = new URL(request.url).searchParams;
      const searchTerm = searchParams.get("searchTerm");
    
      ...
    }