Skip to main content
React Datetime Picker with Example

React Datetime Picker with Example

in this tutorial, We’ll integrate the Date and Time component into the react application. The Datepicker component is the most used in any web application to the select DateTime.

React Datepicker

The react-datepicker package is used to create datatime selector into the react application. React datepicker is a simple and reusable component that can help you integrate the date and time picker with some custom functionality. If you need to use a locale other than the default en-US, you’ll also need to import that into your project from (date-fns).

Install React.js

Let’s create a react app using below command:

npx create-react-app react-data-sample
cd react-data-sample
npm start

Install All dependencies

Install react-datepicker using the following command.

npm install react-datepicker --save

We also install Moment.js separately since the dependency isn’t included in the package. The below command is used to install moment.js package.

npm install moment --save

Let’s install the bootstrap using the following command.

npm install bootstrap --save

The most basic use of the DatePicker can be:

<datepicker selected="{startdate}" onchange="{(date)" ==""> setStartDate(date)} />

How To Add DatePicker

Added below code into our component src/App.js file.

// App.js
import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';
import 'bootstrap/dist/css/bootstrap.min.css';

const Example = () => {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <datepicker selected="{startDate}" onchange="{(date:Date)" ==""> setStartDate(date)} />

we have imported datpicker, moment, bootstrap libraries.

We have set the initial date to today’s date. The user can select the new data from the calendar, it will set the new state with its new values.

You can use onSelect event handler which fires each time some calendar date has been selected:

<datepicker selected="{date}" onselect="{handleDateSelect}" when="" day="" is="" clicked="" onchange="{handleDateChange}" only="" value="" has="" changed="">

How To Select Time From Date picker

You can also include a time picker by adding the showTimeSelect prop.

<datepicker selected="{}" onchange="{(date)" ==""> setStartDate(date)}
  dateFormat="LLL" />

Leave a Reply

Your email address will not be published. Required fields are marked *