React Date Picker Component

To use datepicker in React, you can use the “react-datepicker” package. 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).

You will also need to install React and PropTypes separately since those dependencies aren’t included in the package.

You must also require the CSS file from this package (or provide your own).

Step 1: Install React.js

npx create-react-app reactdates
cd reactdates
npm start

React Datepicker Tutorial Example

Step 2: Install React Date Picker

Install react-datepicker using the following command.

npm install react-datepicker --save

# or

yarn add react-datepicker

We also need to install Moment.js separately since the dependency isn’t included in the package.

Below is a simple example of using the Datepicker in a React view. You will also need to require the CSS file from this package.

npm install moment --save

# or

yarn add moment

Also, install the bootstrap using the following command.

npm install bootstrap --save

# or

yarn add bootstrap

Now we have installed all the frontend libraries.

The next step is to set up the front end.

Step 3: Add Datepicker to the form

Inside the src >> App.js file, replace the following code inside the 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';

class App extends Component {

  constructor (props) {
    super(props)
    this.state = {
      startDate: moment()
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(date) {
    this.setState({
      startDate: date
    })
  }

  handleSubmit(e) {
    e.preventDefault();
    let main = this.state.startDate
    console.log(main.format('L'));
  }

  render() {
    return (
      <div className = "container">
        <h3>React Datepicker Example</h3>
        <form onSubmit={ this.handleSubmit }>
          <div className="form-group">
            <label>Select Date: </label>
            <DatePicker
              selected={ this.state.startDate }
              onChange={ this.handleChange }
              name="startDate"
              dateFormat="MM/dd/yyyy"
            />
          </div>
          <div className="form-group">
            <button className="btn btn-success">Add Date</button>
          </div>
        </form>
      </div>
    );
  }
}

export default App;

Explanation

Now, the <Datepicker /> component has many options to configure.

The most basic use of the DatePicker can be described with:

<DatePicker selected={this.state.date} onChange={this.handleChange} />

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

<DatePicker selected={this.state.date}
  onSelect={this.handleSelect} //when day is clicked
  onChange={this.handleChange} //only when value has changed
/>

The onClickOutside Handler may be helpful to close datepicker in inline mode.

Time picker

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

<DatePicker
  selected={this.state.date}
  onChange={this.handleChange}
  showTimeSelect
  dateFormat="LLL" />

How to Select Time with Date in Datepicker

<DatePicker
  selected={this.state.startDate}
  onChange={this.handleChange}
  name="startDate"
  timeFormat="HH:mm"
  timeIntervals={15}
  timeCaption="time"
  dateFormat="MMMM d, yyyy h:mm aa"
/>

Select Time Only in React Datepicker

<DatePicker
  selected={this.state.startDate}
  onChange={this.handleChange}
  showTimeSelect
  showTimeSelectOnly
  timeIntervals={15}
  timeCaption="Time"
  dateFormat="h:mm aa"
/>
react datepicker example

Step 4: Create the Node.js backend

Inside the root folder of reactdates, create one more folder called backend.

Go inside the folder, open the terminal, and initialize the package.json file using the following command.

npm init -y

Install the following dependencies.

yarn add express body-parser mongoose cors

# or

npm install express body-parser mongoose --save

Also, install the nodemon as a development dependency.

npm install nodemon --save-dev

Now, create one file called server.js and add the following code.

// server.js

const app = require('express')(),
  bodyParser = require('body-parser'),
  cors = require('cors'),
  mongoose = require('mongoose');

  const PORT = process.env.PORT || 4000; 

  app.listen(PORT, () => {
    console.log('Listening on port ' + PORT);
  });

The next thing is to connect the MongoDB database with our node.js application.

If you have not installed the MongoDB database, install it and start the mongodb server.

Type the following command to start the MongoDB server.

mongod

We need to connect our node.js application to the Mongodb database.

Create one file called DB.js inside the backend folder.

// DB.js

module.exports = {
  DB: 'mongodb://localhost:27017/reactdates'
};

Import this DB.js file inside our server.js file and use the Mongoose library to set up the database connection with MongoDB.

We can also use Mongoose to save the data in the database using Mongoose ORM.

Write the following code inside the server.js file to connect our MongoDB application to the Node.js server.

// server.js

const app = require('express')(),
  bodyParser = require('body-parser'),
  cors = require('cors'),
  mongoose = require('mongoose')
  config = require('./DB');

  mongoose.Promise = global.Promise;
  mongoose.connect(config.DB, { useNewUrlParser: true }).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database'+ err)}
  );

  const PORT = process.env.PORT || 4000;

  app.use(bodyParser.json());
  app.use(cors());

  app.listen(PORT, () => {
    console.log('Listening on port ' + PORT);
  });

Save a file, go to a terminal, and start the node.js server using the following command. Ensure you are inside the backend folder root, not the reactdates folder root.

nodemon server

MongoDB Date Tutorial

Now, We have a total of three servers running.

  1. React Development Server.
  2. Node.js Server.
  3. Mongodb Server.

Step 5: Create a model and Express routes.

We must create two folders inside the backend folder called routes and models.

In the models’ folder, create one model called DateModel.js.

// DateModel.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let DateModel = new Schema({
  sDate: {
    type: Date
  },
},{
    collection: 'dates'
});

module.exports = mongoose.model('DateModel', DateModel);

Here, we will store only one field called sDate, whose data type is Date.

In the routes folder, create one file called date.route.js. Then, add the following code inside the date.route.js file.

// date.route.js

const dateRoute = require('express').Router(),
      DateModel = require('../models/DateModel');

dateRoute.route('/add').post(function (req, res) {
  let datemodel = new DateModel(req.body);
  datemodel.save()
    .then(dateSaved => {
    res.status(200).json({'dateSaved': 'Date in added successfully'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

module.exports = dateRoute;

Our backend work is done. When the POST request hits the route: /dates/add, it will save the values inside the mongodb database.

Our final server.js file looks like this.

// server.js
const app = require('express')(),
  bodyParser = require('body-parser'),
  cors = require('cors'),
  mongoose = require('mongoose')
  config = require('./DB'),
  dateRoute = require('./routes/date.route');

  mongoose.Promise = global.Promise;
  mongoose.connect(config.DB, { useNewUrlParser: true }).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database'+ err)}
  );

  const PORT = process.env.PORT || 4000;

  app.use(bodyParser.json());
  app.use(cors());

  app.use('/dates', dateRoute);

  app.listen(PORT, () => {
    console.log('Listening on port ' + PORT);
  });

Step 6: Install Axios and send a POST request.

Type the following command to install the Axios library using the following command. We need to install it on the front end, so please open the terminal inside the reactdates project root.

yarn add axios

# or

npm install axios --save

Now import the axios inside the App.js file and send the data to the Node.js server. Then, finally, write the final code inside the App.js file.

// server.js

import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import axios from 'axios';
 
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: moment()
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(date) {
    this.setState({
      startDate: date
    })
  }

  handleSubmit(e) {
    e.preventDefault();
    let mainDate = this.state.startDate;
    const dateObj = {
      sDate: mainDate.format('L')
    }
    axios.post('http://localhost:4000/dates/add', dateObj)
        .then(res => console.log(res.data));
  }

  render() {
    return (
      <div className = "container">
        <h3>React Datepicker Example</h3>
        <form onSubmit={ this.handleSubmit }>
          <div className="form-group">
            <label>Select Date: </label>
            <DatePicker
              selected={ this.state.startDate }
              onChange={ this.handleChange }
              name="startDate"
              dateFormat="MM/DD/YYYY"
            />
          </div>
          <div className="form-group">
            <button className="btn btn-success">Add Date</button>
          </div>
        </form>
      </div>
    );
  }
}

export default App;

Save the file and go to the browser, select the data, and submit the form, and you can see in the console that our date is successfully saved inside the MongoDB database.

React Datepicker Tutorial

I have submitted four dates. So in the MongoDB database, there are four entries.

Mongoose Date Example Tutorial

That’s it for this tutorial.

Github Code

5 thoughts on “React Date Picker Component”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.