How To Use React-Datepicker In React

Hello developers, in this blog we are gonna learn how to use date picker component in react instead of simple HTML input type date tag

First create a new app :

npx create-react-app react-date-picker

Then install react-date picker in your app:

npm install react-datepicker --save
or 
yarn add react-datepicker

and then import datepicker and CSS file in your component.

import DatePicker from "react-datepicker";
import 'react-datepicker/dist/react-datepicker.min.css'
<DatePicker selected={startDate} onChange={(date) => setStartDate(date)} />

we can also add more functionality to this component

add closeOnScroll={true} to close date-picker automatically while scrolling

you can add minDate and maxDate to prevent users from selecting past dates or max future date

DatePicker
    minDate={new Date()}
    maxDate={new Date().setDate(new Date().getDate() + 7)}
    closeOnScroll
    selected={startDate}
    onChange={(date) => setStartDate(date)}
/>

you can add time input in date-picker

there are two types of time inputs available

1.) add showTimeInput to add time input in which the user can type time or select time from the pop-up

2.) showTimeSelect:

while using timeSelect there is a default time interval of half-hour but you can change time interval by using timeInterval prop

<DatePicker
      showTimeSelect
      timeIntervals={5}   //5 means set interval of 5-5 minutes
      minDate={new Date()}
      maxDate={new Date().setDate(new Date().getDate() + 7)}
      closeOnScroll
      selected={startDate}
      onChange={(date) => setStartDate(date)}
 />


Hope this blog is helpful for you 🙂

Submit a Comment

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

Subscribe

Select Categories