Learn Reactjs Date picker with examples


Datepicker is an important form element of an web page, It is used to select date from user.

Date picker contains input text box and overlay calendar shown on focus input control. It enables to select date and time.

user can use textbox to take date. Why date picker is required?

Date picker has some advantages.

-Force or restrict user to accept the valid dates only

  • Entering user dates manually is error prone, so clicking with date-picker is very smooth and easy

  • Can also customize to add today buttons

  • Styles specific dates with some colours, example holidays

  • Date range can also be added.

In this example, Learn how to integrate date-picker npm library in Reactjs Application.

Let’s get started!

Create a new React Application

Now Let’s create new react application with folder structure using npx create-react-app cli command


npx  create-react-app  react-datepicker-examples

This creates react project folder structure and installs required dependencies.

Go to application root folder, Install react-datepicker into react application


npm install react-datepicker --save

This will installs dependency and add an entry in package.json as below

  "dependencies": {

    "react-datepicker": "^3.4.1",

  }

Simple Date picker in reactJs

This is simple date picker with setting current date into state object

import React, { Component } from 'react';
import DatePicker from "react-datepicker";
class Simpledatepicker extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedDate: new Date(),
        }
    }
    onChangeEvent = event => {
        console.log(event);
        this.setState({ selectedDate: event });
    };

    render() {
        return (
            <div>
                <p> date picker Simple example </p>
                <DatePicker
                
                    selected={this.state.selectedDate}
                    onChange={this.onChangeEvent}
                />
            </div>
        );
    }
}

export default Simpledatepicker;

useState hooks functional component

In similar way, The same class component can be rewritten using functional component and useState hook. These components are also called functional components

hooks in react add functionalities to functional components. Here useState hook adds state to this.

 const [currentDate, setCurrentDate] = useState(new Date());

The above line of code specify two things

  • current date declared as a parameter in useState hook, which is initial value
  • currentDate is state variable that will be initialized with current date returned from useState
  • setCurrentDate is the function that updates state variable, here currentDate.

Steps required to use date picker component.

  • Imported Date picker inside a component
  • selected inside DatePicker is selected date in component.
  • onChange is event handler, called whenever component change its value
  • It calls setCurrentDate to selected new date

Complete component code:

import React, { useState } from 'react';
import DatePicker from "react-datepicker";

const Datepickerhooks = () => {
    const [currentDate, setCurrentDate] = useState(new Date());

    return (
        <div>
            <DatePicker selected={currentDate} onChange={date => setCurrentDate(date)} />

        </div>
    );
};

export default Datepickerhooks;

And the output,

Button disabled form invalid button

Add placeholder to date picker component

Placeholder is an initial value to displayed in input box before selecting date value.Placeholder is a string and not empty and selected value should be false values like empty or false. Please note that placeholder value only shown when this.props.datevariable or this.state.variable value is false values.

 <DatePicker
                    placeholder ="Please selecte Date of birth"
                    selected={this.state.selectedDate}
                    onChange={this.onChangeEvent}
/>

Display time picker to component

By default, date picker not shows time information in date picker.

There are showTimeInput option displays current time + select icon to change time as show below

<DatePicker showTimeInput selected={currentDate} onChange={date => setCurrentDate(date)} />

Output:

Button disabled form invalid button

showTimeSelect attribute adds time picker component into a component

Time will be shown in range of 30 minutes interval, These intervals can be configure using timeIntervals

<DatePicker showTimeSelect selected={currentDate} onChange={date => setCurrentDate(date)} />

Output:

Button disabled form invalid button

Complete example code:

import React, { useState } from 'react';
import DatePicker from "react-datepicker";

const DatepickerTimehooks = () => {
    const [currentDate, setCurrentDate] = useState(new Date());

    return (
        <div>
            <DatePicker showTimeInput
                timeFormat="HH:mm:ss"
                timeIntervals={15}
                timeCaption="time"
                showTimeSelect selected={currentDate} onChange={date => setCurrentDate(date)} />

        </div>
    );
};

export default DatepickerTimehooks;

timeFormat is an formatting the time to be displayed on time picker. timeIntervals is an interval of time to be displayed on it timeCaption is text displayed on caption shown to component.

To display time picker without date picker

set date format to YYYY/mmm/dd in a component

by default, date picker displays date dd/mm/yyyy format.

If custom date format is required, Then dateFormat option is to be used

 <div>
    <DatePicker
        dateFormat="yyyy/MMM/dd"
        selected={currentDate} onChange={date => setCurrentDate(date)} />
</div>

Output:

Button disabled form invalid button

Add css styles or class names in date picker component

className attribute adds styles to input box in date picker. And its value is CSS classname declared in css class at global or component level

import React, { useState } from 'react';
import DatePicker from "react-datepicker";

const DatepickerComponent = () => {
    const [currentDate, setCurrentDate] = useState(new Date());

    return (
        <div>
            <DatePicker
                dateFormat="yyyy/MM/dd"

                className="inputStyles"
                selected={currentDate} onChange={date => setCurrentDate(date)} />

        </div>
    );
};

export default DatepickerComponent;

Declared inputStyles in App.css

.inputStyles {
    outline: none;
    border-radius: 5px;
    border: 1px solid blue;
    font-weight: 700;
}
Similar Posts