![]() |
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: Steps to Create NextJS App:Step 1: Create a NextJS application using the following command. npx create-next-app@latest gfg Step 2: It will ask you some questions, so choose the following. √ Would you like to use TypeScript? ... No Step 3: After creating your project folder i.e. gfg, move to it using the following command. cd gfg Approach 1: searchParams parameterIn this approach, We have used a searchParams parameter to access the query params. searchParams provides us an object and by using that object we can access query parameters. In this approach, we have made a form. when you submit the form, all the values of the form will sent to the form data server component as a URL query. Syntax: export default function Page({ searchParams }) {
const params = searchParams
return (
<>
<h2> {params.value}</h2>
</>
)
} Example 1: The below example demonstrate to get query params using searchParams parameter in server component.
To run the application, use the following command:npm run dev Output: Approach 2 : useSearchParams() methodIn 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.
To run the application, use the following command: npm run dev Output: |
Reffered: https://www.geeksforgeeks.org
ReactJS |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |