How to use datepicker in react js?
December 20, 2024Hi Friends 👋,
Welcome To aHoisting!
To use datepicker you have to import datepicker
from 'react-datepicker'
that’s how you can use datepicker in react js.
Today, I am going to show you, how to use datepicker in react js.
Installation
Install the following packages to use react-datepicker in react js.
npm
npm install react-datepicker
yarn
yarn add react-datepicker
Table of contents
- Install and create a new React app.
- Import react component.
- Create a Component.
Let’s start with the first step.
Step 1: Install and create a new React app.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import react component.
After installing, you have to import your React component.
import React, { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
Step 3: Create a Component.
You can use dateFormat="yyyy/MM/dd"
to use datepicker in react js.
<div>
<h3>Select a Date:</h3>
<DatePicker
selected={startDate}
onChange={(date) => setStartDate(date)} // Callback to update the state
dateFormat="yyyy/MM/dd" // Optional: Set the desired date format
isClearable // Optional: Show a clear button
placeholderText="Select a date" // Optional: Placeholder text
/>
</div>
Use datepicker example.
The below code is an example of a React. You have to import react
and 'react-datepicker'
to use datepicker in react js.
App.js
import React, { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css'; // Import the CSS file
const App = () => {
const [startDate, setStartDate] = useState(new Date());
return (
<div>
<h3>Select a Date:</h3>
<DatePicker
selected={startDate}
onChange={(date) => setStartDate(date)} // Callback to update the state
dateFormat="yyyy/MM/dd" // Optional: Set the desired date format
isClearable // Optional: Show a clear button
placeholderText="Select a date" // Optional: Placeholder text
/>
</div>
);
};
export default App;
In the above code example, I have used the 'react-datepicker'
to use datepicker in react js.
Check the output of the above code.
All the best 👍