Why Use a Date Picker in React?
Date pickers simplify date input, making it user-friendly and avoiding the errors that manual date typing can cause. They’re commonly used in applications that involve scheduling, booking and filtering by date and are especially beneficial in forms that need accurate date input.
Setting Up react-datepicker
To use a date picker in React, you’ll need the react-datepicker library, which provides a flexible date picker component with various options.
Step 1: Installing react-datepicker
To install react-datepicker, use the following command:
npm install react-datepicker
Since react-datepicker requires styling, you should also import its CSS file. Install date-fns (a popular date utility library) for additional date manipulation options.
npm install date-fns
Step 2: Importing the Date Picker Component and CSS
Once the library is installed, import the react-datepicker component and CSS styles into your file.
import React, { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
Basic Usage of React Date Picker
Let’s start with a simple example of using a date picker component in React. In this example, we’ll initialize the date picker with a default date and use the useState hook to manage the selected date.
import React, { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
function BasicDatePicker() {
const [selectedDate, setSelectedDate] = useState(null);
return (
<div>
<h3>Select a Date</h3>
<DatePicker
selected={selectedDate}
onChange={(date) => setSelectedDate(date)}
placeholderText="Choose a date"
/>
</div>
);
}
export default BasicDatePicker;
In this example:
- selected is bound to selectedDate, and onChange updates selectedDate when a new date is selected.
- The placeholder text gives a hint to users to pick a date.
Customizing the Date Picker
The react-datepicker component offers various customization options for formats, date ranges, and appearance.
Customizing Date Format
By default, the date format follows the browser’s locale. You can set a custom date format using the dateFormat property. For instance, to display dates in MM/dd/yyyy format:
<DatePicker
selected={selectedDate}
onChange={(date) => setSelectedDate(date)}
dateFormat="MM/dd/yyyy"
/>
Limiting Date Range
To restrict users from selecting dates outside a certain range (e.g., disabling past or future dates), use the minDate and maxDate properties.
<DatePicker
selected={selectedDate}
onChange={(date) => setSelectedDate(date)}
minDate={new Date()} // Disables past dates
maxDate={new Date(2025, 11, 31)} // Limits dates until December 31, 2025
/>
Disabling Specific Days (e.g., Weekends)
You may want to disable certain days like weekends. This can be done using the filterDate property, which takes a function that returns true or false based on whether a date should be selectable.
<DatePicker
selected={selectedDate}
onChange={(date) => setSelectedDate(date)}
filterDate={(date) => date.getDay() !== 6 && date.getDay() !== 0}
/>
In this example, filterDate disables Saturdays (6) and Sundays (0).
Adding Time Selection
react-datepicker also allows users to pick a specific time by enabling the showTimeSelect option. You can combine this with dateFormat to create a date-time picker.
<DatePicker
selected={selectedDate}
onChange={(date) => setSelectedDate(date)}
showTimeSelect
dateFormat="MMMM d, yyyy h:mm aa"
/>
Adding a Custom Calendar Icon
Instead of showing the date picker directly, you might want a calendar icon that opens the date picker. Here’s an example with a button icon that triggers the date picker.
import React, { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { FaCalendarAlt } from 'react-icons/fa';
function IconDatePicker() {
const [selectedDate, setSelectedDate] = useState(null);
return (
<div>
<DatePicker
selected={selectedDate}
onChange={(date) => setSelectedDate(date)}
customInput={<FaCalendarAlt size={20} />}
/>
</div>
);
}
export default IconDatePicker;
Styling and Theming the Date Picker
The date picker can be styled further using CSS. You can modify the default CSS file or create custom classes and apply them using the className property. For example:
.custom-datepicker {
border: 2px solid #007BFF;
padding: 10px;
font-size: 16px;
}
Then apply the custom class:
<DatePicker
selected={selectedDate}
onChange={(date) => setSelectedDate(date)}
className="custom-datepicker"
/>
Handling Date Validation
It’s important to validate the date input to ensure it meets application requirements. Here’s an example of a simple validation that checks if a date has been selected:
function DatePickerWithValidation() {
const [selectedDate, setSelectedDate] = useState(null);
const [error, setError] = useState('');
const handleDateChange = (date) => {
setSelectedDate(date);
if (!date) {
setError('Please select a date.');
} else {
setError('');
}
};
return (
<div>
<DatePicker
selected={selectedDate}
onChange={handleDateChange}
placeholderText="Select a date"
/>
{error && <p style={{ color: 'red' }}>{error}</p>}
</div>
);
}
In this example:
- error holds any validation messages.
- If no date is selected, an error message prompts the user to select a date.
Example Use Case: Booking Form with Date Picker
Here’s a complete example of using the date picker within a booking form where a user selects a start and end date for their booking.
import React, { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
function BookingForm() {
const [startDate, setStartDate] = useState(null);
const [endDate, setEndDate] = useState(null);
return (
<div>
<h3>Book Your Stay</h3>
<div>
<label>Check-In Date:</label>
<DatePicker
selected={startDate}
onChange={(date) => setStartDate(date)}
minDate={new Date()}
placeholderText="Choose a start date"
/>
</div>
<div>
<label>Check-Out Date:</label>
<DatePicker
selected={endDate}
onChange={(date) => setEndDate(date)}
minDate={startDate}
placeholderText="Choose an end date"
/>
</div>
</div>
);
}
export default BookingForm;