skip to Main Content

I’m using Next.js with TypeScript and I want to navigate to a new page and want to include the URL parameters as well. How do i do that?

For example I’m at http://localhost:3000/ and I want to navigate to http://localhost:3000/path?queryParam=value by clicking on a button.

2

Answers


  1. Chosen as BEST ANSWER
    1. You can only do this on a component rendered on client side, so you need to include 'use client' on the top of your component.
    2. Use the useRouter hook from next/navigation.
    3. Instantiate a new URLSearchParams.
    4. Set all URL parameters to the new URLSearchParams.
    5. Use the router.push function to navigate to the new page, including the given parameters.

    For example:

    'use client'
     
    import { useRouter } from 'next/navigation'
     
    export default function Page() {
      const router = useRouter()
     
      return (
        <button
          onClick={() => {
            const params = new URLSearchParams();
            params.set("queryParam", "value");
    
            router.push(`/path?${params}`);
          }}
        />
      )
    }
    

    Sources:


  2. You can achieve this by combining the usePathname, useRouter and the useSearchParams hooks.

    "use client"
    
    import { usePathname, useSearchParams, useRouter } from "next/navigation";
    
    const SomeComponent = () => {
       const pathname = usePathname();
       const { push } = useRouter();
       const searchParams = useSearchParams();
    
       const onClickHandler = () => {
          const params = new URLSearchParams(searchParams);
    
          if (queryParam) {
             params.set("queryParam", encodeURIComponent("some value"));
          } else {
             params.delete("queryParam");
          }
    
          push(`${pathname}?${params.toString()}`); //You can use the replace method if you want to replace the history
    
       }
    
       return (
          <button onClick={onClickHandler}>Go to URL</button>
       )
    }
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search