Open In App

How to Add Simple DatePicker in Next.js ?

Last Updated : 30 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to learn how we can add a Simple Datepicker in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally.

Approach

To add our DatePicker we are going to use the react-datepicker package. The react-datepicker package helps us to add a DatePicker anywhere in our app. So first, we will install the react-datepicker package and then we will add a DatePicker on our homepage.

Steps To Create Next App And Install Modules

Step 1: Initialize NextJS Application

You can create a new NextJs project using the below command:

npx create-next-app gfg

Step 2: Switch to the Project Directory

Use the below command to open the project folder in the terminal

cd gfg

Step 3: Install the required package

Now we will install the react-datepicker package using the below command:

npm i react-datepicker

Project Structure:

It will look like this

The updated dependencies in the package.json are:

"dependencies": {
"next": "13.4.12",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-datepicker": "^4.11.0"
},

Example: This example imports the data picker component from the react-date-picker package.

JavaScript
// Filename - pages/index.jsimportReact,{useState}from'react';importDatePickerfrom"react-datindex.jsepicker";import"react-datepicker/dist/react-datepicker.css";exportdefaultfunctionGfgDatePicker(){const[startDate,setStartDate]=useState(newDate());return(<div><h4>GeeksforGeeks-DatePicker</h4><DatePickerselected={startDate}onChange={(date)=>setStartDate(date)}/></div>);}

Explanation: In the above example first, we are importing the DatePocker from the installed package and useState hook from react. After that, we are using creating a constant variable and used the useState hook to store the values. Then we will add our datepicker using the DatePicker component.

Steps to run the application: Run the below command in the terminal to run the app.

npm run dev

Output:



Next Article

Similar Reads

close