Approach 2 : useSearchParams() method
In this approach, We are going to use a useSearchParams() method to access a query parameters in a client component. useSearchParams() provides a different methods such as get(), getAll(), keys(), values(), entries(), forEach() and toString() to access the query parameters.
Syntax:
'use client';
export default function Page() {
const name = useSearchParams().get('name');
return (
<>
<h2> {name}</h2>
</>
)
}
Example 2: The below example demonstrate to get query params using useSearchParams() method in a client component.
//File path: /page.js
export default function Home() {
return (
<>
<div style={{ margin: "25px" }}>
<h1>Form</h1>
<form method="get" action="/formdata">
<input type="text" name="name"
placeholder="Enter your Name" /> <br /> <br />
<input type="email" name="email"
placeholder="Enter your Email Id" /> <br /> <br />
<input type="number" name="age"
placeholder="Enter your Age" /> <br /> <br />
<button type="submit">Submit</button>
</form>
</div>
</>
);
}
//File path: formdata/page.js
'use client';
import { useSearchParams } from "next/navigation"
export default function Page() {
const name = useSearchParams().get('name')
const email = useSearchParams().get('email')
const age = useSearchParams().get('age')
return (
<>
<h1>Form Data</h1>
<h2>Name: {name}</h2>
<h2>Email: {email}</h2>
<h2>Age: {age}</h2>
</>
)
}
To run the application, use the following command:
npm run dev
Output:
How to Get query params using Server component in Next.js ?
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications.
We will discuss different approaches to get query params using the server component in NextJS:
Table of Content
- Approach 1: searchParams parameter
- Approach 2 : useSearchParams() method
Contact Us