Integrating a date and time picker in a React.js app can be done using various libraries that provide pre-built components for selecting dates and times. One popular library for this purpose is react-datepicker
. Here's how you can integrate react-datepicker
into your React.js app:
Install react-datepicker
:
bashnpm install react-datepicker
Import and Use react-datepicker
Component:
jsximport React, { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
const DateTimePicker = () => {
const [selectedDate, setSelectedDate] = useState(null);
return (
<div>
<h2>Select Date and Time</h2>
<DatePicker
selected={selectedDate}
onChange={(date) => setSelectedDate(date)}
showTimeSelect
timeFormat="HH:mm"
timeIntervals={15}
dateFormat="MMMM d, yyyy h:mm aa"
timeCaption="Time"
placeholderText="Select date and time"
/>
</div>
);
};
export default DateTimePicker;
In this example:
DatePicker
component from react-datepicker
.selectedDate
).DatePicker
component is rendered with various props to configure its behavior:selected
: Holds the selected date and time.onChange
: Callback function invoked when the selected date and time change.showTimeSelect
: Enables time selection.timeFormat
: Specifies the time format (24-hour format in this case).timeIntervals
: Defines the time interval between selectable times (15 minutes in this case).dateFormat
: Specifies the date format.timeCaption
: Label for the time select dropdown.placeholderText
: Placeholder text displayed when no date is selected.Style react-datepicker
(Optional):
You can customize the appearance of react-datepicker
by overriding its CSS classes or providing custom CSS styles.
Use DateTimePicker
Component in Your Application:
You can now use the DateTimePicker
component wherever you need a date and time picker in your React application:
jsximport React from 'react';
import DateTimePicker from './DateTimePicker';
const App = () => {
return (
<div>
<DateTimePicker />
</div>
);
};
export default App;
By following these steps, you can easily integrate a date and time picker into your React.js application using react-datepicker
. This library provides a simple and customizable solution for handling date and time selection in your application.