How to Implement Datepicker in React with Example

26751 views 2 years ago React

Welcome to How to Implement and use Datepicker in React application! In this tutorial, you will learn the step-by-step process of integrating and using react-datepicker modules in React.js.

The React datepicker is a compelling and reusable component used for displaying the dates using a calendar dialog.

There are lots of datepicker packages available, but we are going to use the React Date Picker package to display date and time in a React application.

React Datepicker Example

The react-datepicker package offers easy customization and allows you to add Date and time through an HTML input field.

You have to install React and PropTypes independently as these dependencies are not incorporated in the package.

Let us start creating a new React project.

Create a New React App

To work with datepicker, calendar, and date/time, you must have a basic React app. The create-react-app helps to install a brand new react app using the terminal.

Run the following command:

npx create-react-app react-datepicker-app

Get inside the project folder:

cd react-datepicker-app

Start the new React app:

npm start

You can check the app on: localhost:3000

Install Datepicker in React App

Run the following command to install the react-datepicker package.

Install the package via npm:

npm install react-datepicker --save

Install via yarn:

yarn add react-datepicker

Install Bootstrap UI Framework

To add the ready-made styling in datepicker, you can use Bootstrap. Its a Sleek, intuitive, and powerful front-end framework for faster and easier web development.

Run the command to install Bootstrap via npm:

npm install bootstrap --save

Run the command to install via yarn:

yarn add bootstrap

Implement Simple Datepicker with React Form

Open the src/App.js file and delete the old code from the file and add the given code below.

import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import "react-datepicker/dist/react-datepicker.css";
import 'bootstrap/dist/css/bootstrap.min.css';
class App extends Component {
  constructor (props) {
    super(props)
    this.state = {
      startDate: new Date()
    };
    this.handleChange = this.handleChange.bind(this);
    this.onFormSubmit = this.onFormSubmit.bind(this);
  }
  handleChange(date) {
    this.setState({
      startDate: date
    })
  }
  onFormSubmit(e) {
    e.preventDefault();
    console.log(this.state.startDate)
  }
  render() {
    return (
      <form onSubmit={ this.onFormSubmit }>
        <div className="form-group">
          <DatePicker
              selected={ this.state.startDate }
              onChange={ this.handleChange }
              name="startDate"
              dateFormat="MM/dd/yyyy"
          />
          <button className="btn btn-primary">Show Date</button>
        </div>
      </form>
    );
  }
}
export default App;

First, we imported the main packages Datepicker and Bootstrap in the React template.

We define the form and bind the handleChange and onFormSubmit events calendar component. These events will trigger when a user submits or change the Datepicker’s input value.

The Datepicker form state is initialized with a new Date() object inside the constructor.

We initiate datepicker with the following directive, we have also attached some properties with it.

<DatePicker
   selected={ this.state.startDate }
   onChange={ this.handleChange }
   name="startDate"
   dateFormat="MM/dd/yyyy"
   />

The React Datepicker component comes with lots of properties to manipulate the Datepicker.

React Time Picker Example

The time picker displays a time list from the list; a user can choose time value using the React calendar.

Add showTimeSelect directive in component, and it will add the time list along with the calendar.

You can also add the date format, timeIntervals, timeFormat, and timeCaption in timepicker.

import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import "react-datepicker/dist/react-datepicker.css";
import 'bootstrap/dist/css/bootstrap.min.css';
class App extends Component {
  constructor (props) {
    super(props)
    this.state = {
      startDate: new Date()
    };
    this.handleChange = this.handleChange.bind(this);
    this.onFormSubmit = this.onFormSubmit.bind(this);
  }
  handleChange(date) {
    this.setState({
      startDate: date
    })
  }
  onFormSubmit(e) {
    e.preventDefault();
    console.log(this.state.startDate)
  }
  render() {
    return (
      <form onSubmit={ this.onFormSubmit }>
        <div className="form-group">
          <DatePicker
              selected={ this.state.startDate }
              onChange={ this.handleChange }
              showTimeSelect
              timeFormat="HH:mm"
              timeIntervals={20}
              timeCaption="time"
              dateFormat="MMMM d, yyyy h:mm aa"
          />
          <button className="btn btn-primary">Show Date</button>
        </div>
      </form>
    );
  }
}
export default App;

Localize Datepicker

The date picker relies on date-fns internationalization to localize display elements.

English is the default locale, check out the following 3 methods to set the locale:

  • registerLocale (string, object): loads an imported locale object from date-fns.
  • setDefaultLocale (string): sets a registered locale as the default for all datepicker instances.
  • getDefaultLocale: returns a string showing the currently set default locale.

Import the following services to set the locale for calendar view.

<DatePicker
  locale="es"
/>

Locales can be modified by changing the locale code using the below method, and you can visit date-fns internationalization to check out the supported languages code.

setDefaultLocale('es')

React Calendar Date Range Example

In this step, we are going to implement date range functionality in React Calendar using minDate and maxDate property.

Import the addDays API from “date-fns” library at the top of your React component. It adds the specified number of days to the assigned date to set the date range.

import addDays from 'date-fns/addDays'

The addDays() method takes two parameters:

date: The date that needs to be updated.

amount: The amount of days that needs to be included.

The following example helps you set the date range from the current date to the next 7 days in the React calendar.

The min and max dates to implement the date range in React Calendar.

render() {
    return (
      <form onSubmit={ this.onFormSubmit }>
        <div className="form-group">
          <DatePicker
              selected={ this.state.startDate }
              onChange={ this.handleChange }
              showTimeSelect
              timeFormat="HH:mm"
              timeIntervals={20}
              timeCaption="time"
              dateFormat="MMMM d, yyyy h:mm aa"
              minDate={new Date()}
              maxDate={addDays(new Date(), 7)}
          />
          <button className="btn btn-primary">Show Date</button>
        </div>
      </form>
    );
  }

Here is the full code that belongs to src/App.js

import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import addDays from 'date-fns/addDays'
import "react-datepicker/dist/react-datepicker.css";
import 'bootstrap/dist/css/bootstrap.min.css';
class App extends Component {
  constructor (props) {
    super(props)
    this.state = {
      startDate: new Date()
    };
    this.handleChange = this.handleChange.bind(this);
    this.onFormSubmit = this.onFormSubmit.bind(this);
  }
  handleChange(date) {
    this.setState({
      startDate: date
    })
  }
  onFormSubmit(e) {
    e.preventDefault();
    console.log(this.state.startDate)
  }
  render() {
    return (
      <form onSubmit={ this.onFormSubmit }>
        <div className="form-group">
          <DatePicker
              selected={ this.state.startDate }
              onChange={ this.handleChange }
              showTimeSelect
              timeFormat="HH:mm"
              timeIntervals={20}
              timeCaption="time"
              dateFormat="MMMM d, yyyy h:mm aa"
              minDate={new Date()}
              maxDate={addDays(new Date(), 7)}
          />
          <button className="btn btn-primary">Show Date</button>
        </div>
      </form>
    );
  }
}
export default App;

i hope you like this article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com