Complete React Datepicker Tutorial with Examples


In this tutorial, you will learn how to use React datepicker in your React project. You will learn from a basic example to a specific use case by creating a hotel booking component using React-Datepicker.

React-datepicker is a simple and reusable component for React. This component currently has around 314 contributors with more than 600.000 weekly downloads which makes this component become one of the most popular libraries for React projects.

React Datepicker

Prequisities

In this tutorial, you will need a configured computer and also basic Javascript & React knowledge. Make sure you have node and npm installed on your computer. The first step of the configuration step is to install create-react-app globally.

npm i -g create-react-app

After the create-react-app is installed, we will need to create a new project with this library. To do that, you can use:

npx create-react-app datepicker-app

Then after successfully creating the project, go to the project folder, install the required package and start the project.

// go to the project folder
cd datepicker-app

// install the required package
npm i --save react-datepicker
npm i --save moment

// start the project
npm start

Basic Implementation: Default

Before starting anything, you will need to put the CSS file into your project. Insert the following code into your project. Basically, you can put this anywhere inside your project, but in this tutorial, we will only use the App.js file, so put this on our code:

// import required react-datepicker styling file
import "react-datepicker/dist/react-datepicker.css";

Then we can start to implement this by importing the DatePicker component from react-datepicker. The mandatory props that we need for this component are only selected and onChange.

The selected props take a date-format value to represent the value of this component, while onChange will act as a handler function to change the selected value. The onChange function takes a date as an argument and the only thing we need to do on this function is to change the value of the selected date. See the example below for implementation on our App.js file:

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

// import required css from library
import "react-datepicker/dist/react-datepicker.css";

// main implementation. using selected and onChange as main props to get and change the selected date value
const App = () => {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <DatePicker 
      selected={startDate} 
      onChange={date => setStartDate(date)} 
    />
  );
};

export default App;

Basic Implementation: Time Picker

We can use this component as a time-picker by using showTimeSelect props. Times will be displayed at a 30-minute interval by default. We can format how the date will be displayed by using the dateFormat props. In this case, because we want to display the time inside the component, let’s use dateFormat="Pp". To implement this on our project, change our App.js to looks like this:

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

// import required css from library
import "react-datepicker/dist/react-datepicker.css";

// time-picker component. using showTimeSelect as a main props and works with basic functionality on react-datepicker that explained above
const App = () => {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <DatePicker
      selected={date}
      onChange={handleDateChange}
      showTimeSelect
      dateFormat="Pp"
    />
  );
};

export default App;

Month & Year Picker

Besides date & time, the ability to pick a month & year is an important thing to have here. This component also has the feature to select month & year. Just make sure we use the correct format of dateFormat to optimize the features. Change our App.js with the following code:

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

// import required css from library
import "react-datepicker/dist/react-datepicker.css";

// time-picker component. using showTimeSelect as a main props and works with basic functionality on react-datepicker that explained above
const App = () => {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <>
      // month picker implementation. using showMonthYearPicker as a main props
      <DatePicker
        selected={date}
        onChange={handleDateChange}
        showMonthYearPicker
        dateFormat="MM/yyyy"
      />

      // month picker implementation. using showYearPicker as a main props
      <DatePicker
        selected={date}
        onChange={handleDateChange}
        showYearPicker
        dateFormat="yyyy"
      />
    </>
  );
};

export default App;

Advanced Example: Booking Hotel Date-Picker

Now, let’s go to the next level. We are going to create a booking hotel date-picker component using react-datepicker. The goal is to build two react-datepicker components, make both connected as check-in and check-out date, and then display the selected dates.

NOTE: In this tutorial, we are only using the single *App.js* file and the code examples below will explain section by section. By the end of this tutorial, you will get the complete code of the whole page and an additional styling file.

First, all we need to do is to create a basic component for check-in and check-out. We don’t really need to use a lot of props here, besides the necessary one, we will only use the minDate props to put a minimum date limit for the user. Also, put some element wrapper and label just to make sure the UI looks neat. Place this code inside your App.js file at the return section:

// import React
import React, { useState } from "react";
...

...
return (
  <div className="input-container">
    <div>
      <label>Check-in</label>
      <DatePicker
        selected={checkInDate}
        minDate={new Date()}
        onChange={handleCheckInDate}
      />
    </div>
    <div>
      <label>Check-out</label>
      <DatePicker
        selected={checkOutDate}
        minDate={checkInDate}
        onChange={handleCheckOutDate}
      />
    </div>
  </div>
)
...

How the above code defines the minDate value? For the check-in component, it’s simply using the current date as a minDate, the user cannot pick a date before today. And for the check-out component, we can use the checkInDate value, which means, the user cannot pick a date before the check-in date.

The next step will be defining how we are going to save the value on our state, and how each handle change function works. For this, the main idea is to simply create a state for each checkInDate and checkOutDate value and save the date there. The only difference is because the minDate of the check-out component will depend on the checkInDate value, we will need to reset the checkOutDate value anytime the checkInDate value changed. So, here is the code you need to add to your App.js file:

// import React
import React, { useState } from "react";
...

const App = () => {
  // define check-in and check-out state
  const [checkInDate, setCheckInDate] = useState(null);
  const [checkOutDate, setCheckOutDate] = useState(null);

  // define handler change function on check-in date
  const handleCheckInDate = (date) => {
    setCheckInDate(date);
    setCheckOutDate(null);
  };

  // define handler change function on check-out date
  const handleCheckOutDate = (date) => {
    setCheckOutDate(date);
  };
...

The last part is we need to display the summary of the booking. It will only be displayed when both check-in and check-out date have the value. For this case, we will use moment.js to format the date. Here is the code, add this to your App.js file below the input component:

// import React
import React, { useState } from "react";
...

return(
  ...
  // summary secton 
  {checkInDate && checkOutDate && (
    <div className="summary">
      <p>
        You book a hotel from {moment(checkInDate).format("LL")} to{" "}
        {moment(checkOutDate).format("LL")}.
      </p>
    </div>
  )}
  ...
)

...

The complete code will of your App.js will be something like this:

import React, { useState } from "react";
import DatePicker from "react-datepicker";
import moment from "moment";
import "./App.css";
import "react-datepicker/dist/react-datepicker.css";

function App() {
  const [checkInDate, setCheckInDate] = useState(null);
  const [checkOutDate, setCheckOutDate] = useState(null);

  const handleCheckInDate = (date) => {
    setCheckInDate(date);
    setCheckOutDate(null);
  };

  const handleCheckOutDate = (date) => {
    setCheckOutDate(date);
  };

  return (
    <div className="App">
      <div className="input-container">
        <div>
          <label>Check-in</label>
          <DatePicker
            selected={checkInDate}
            minDate={new Date()}
            onChange={handleCheckInDate}
          />
        </div>
        <div>
          <label>Check-out</label>
          <DatePicker
            selected={checkOutDate}
            minDate={checkInDate}
            onChange={handleCheckOutDate}
          />
        </div>
      </div>
      {checkInDate && checkOutDate && (
        <div className="summary">
          <p>
            You book a hotel from {moment(checkInDate).format("LL")} to{" "}
            {moment(checkOutDate).format("LL")}.
          </p>
        </div>
      )}
    </div>
  );
}

export default App;

Here is some of App.css file for styling purpose:

.App {
  text-align: center;
  height: 100vh;
  flex: 1;
  justify-content: center;
  align-items: center;
  padding: 40px;
}

.input-container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.input-container .react-datepicker-wrapper {
  margin: 12px 0;
  width: 100%;
}

.input-container .react-datepicker-wrapper input {
  padding: 4px 12px;
}

.summary {
  font-size: 18px;
}

Conclusion

Now we know how to use a react-datepicker on our project. After following the basic and advanced tutorial, we will be able to use this great component for our next project. I hope you understand every step in this tutorial, if you have any questions or suggestions, please let us know in the comment section below.


Share on social media

//