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.
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>
)
}
- 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. - Use the
useRouter
hook fromnext/navigation
. - Instantiate a new
URLSearchParams
. - Set all URL parameters to the new
URLSearchParams
. - 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:
- Next.js useRouter
- MDN Web Docs URLSearchParams