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.

댓글

이 블로그의 인기 게시물

Using the MinIO API via curl

How to split a list into chunks of 100 items in JavaScript, 자바스크립트 리스트 쪼개기

HTML Inline divisions at one row by Tailwind

Boilerplate for typescript server programing

가속도 & 속도

Gradle multi-module project

How to checkout branch of remote git, 깃 리모트 브랜치 체크아웃

CDPEvents in puppeteer

Sparse encoder

Reactjs datetime range picker