skip to Main Content

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?

2

Answers


  1. I believe that gonna help you

    {
              path: "search",
              element: <SearchResults />,
              loader: async ({ params, request }) => {
                const url = new URL(request.url);
                const searchTerm = url.searchParams.get("q");
                return searchProducts(searchTerm);
              },
    },
    
    Login or Signup to reply.
  2. 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");
    
      ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search