React datetime range picker
To implement a datetime range picker in React, you can use various libraries that provide this functionality. One popular library is react-dates. Here's an example of how you can use it to create a datetime range picker:
First, install the required dependencies by running the following command:
npm install react-dates moment
Once the installation is complete, you can use the following code as an example:
import React, { useState } from 'react';
import { DateRangePicker } from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';
import 'react-dates/initialize';
const DateTimeRangePicker = () => {
const [startDate, setStartDate] = useState(null);
const [endDate, setEndDate] = useState(null);
const [focusedInput, setFocusedInput] = useState(null);
const handleDateChange = ({ startDate, endDate }) => {
setStartDate(startDate);
setEndDate(endDate);
};
return (
<div>
<DateRangePicker
startDate={startDate}
startDateId="start_date"
endDate={endDate}
endDateId="end_date"
onDatesChange={handleDateChange}
focusedInput={focusedInput}
onFocusChange={setFocusedInput}
numberOfMonths={1}
isOutsideRange={() => false}
showClearDates
small
/>
</div>
);
};
export default DateTimeRangePicker;
In this example, we use the useState hook to manage the selected startDate and endDate values. The focusedInput state is used to control which input field is focused.
The handleDateChange function is called whenever the user selects a new date range. It updates the startDate and endDate states accordingly.
The DateRangePicker component from react-dates is rendered, using the startDate, startDateId, endDate, and endDateId props to bind the input fields with their respective state values. The onDatesChange prop is used to call the handleDateChange function when the date range changes.
You may need to adjust the styling and customize the behavior based on your requirements. Remember to import the required CSS files from react-dates and initialize it with react-dates/initialize to ensure the styles and functionality work properly.
With this setup, you can use the DateTimeRangePicker component in your application to allow users to select a date and time range.
댓글
댓글 쓰기