Hi everyone, Today we will see how to change the URL parameters in real time using Next.js, it’s truly simple, now let’s begin!
Setup
First, create a Next.js project using npx:
$ npx create-next-app live-params
Then, create a components folder and create a new file named Form.tsx
mkdir components
touch components/Form.tsx
The file structure should look like this:
.
├── app
│ ├── components
│ │ ├── Form.tsx
│ ├── favicon.ico
│ ├── globals.css
│ ├── layout.tsx
│ ├── page.module.css
│ └── page.tsx
├── public
│ ├── next.svg
│ └── vercel.svg
├── package-lock.json
├── next-env.d.ts
├── next.config.js
├── package.json
├── README.md
└── tsconfig.json
Now put the following code in Form.tsx:
'use client';
import { usePathname, useSearchParams } from 'next/navigation';
import { useRouter } from 'next/navigation';
export default function Form() {
const searchParams = useSearchParams();
const pathname = usePathname();
const { replace } = useRouter();
const handleSearch = (term: string) => {
const params = new URLSearchParams(searchParams);
if (term) {
params.set('query', term);
} else {
params.delete('query');
}
replace(`${pathname}?${params.toString()}`);
};
return (
<input
placeholder="test"
onChange={(event) => handleSearch(event.target.value)}
defaultValue={searchParams.get("query"?.toString()) || ''}
/>
);
}
Explanation
When we write in the input, the value is set a parameter called query and replace the URL with the pathname and the params respectively
Add the following code in your app/page.tsx
import Form from "@/components/Form";
export default function Home({
searchParams,
}: {
searchParams: { query: string };
}) {
return (
<>
<h1>Live Params</h1>
<Form />
<p>Current Param: {searchParams.query}</p>
</>
);
}
With searchParams we can get the URL parameters and use it
Result
Conclusion
With this, you can use the caught parameter in an API request, filter data, etc. If you use this in an API request, it’s recommended to use the use-debounce package to prevent unnecessary requests while typing in the input field
If you learned something new from this article, you can give me a clap, I will thank you ❤