admin管理员组

文章数量:1410682

I want to create a calendar like this.

The Issue is I don't know how to add Apply and Cancel button in It. I have tried multiple solutions, But failed to get desired solution.

Through this block of code of I got this.

Kindly help me to add Button in react-datepicker.

import DatePicker from 'react-datepicker'
import 'react-datepicker/dist/react-datepicker.css'
const [startDate, setStartDate] = useState(new Date())

<DatePicker
 selected={startDate}
 className='w-[210px] p-3 text-sm font-[Inter-Regular] outline-none text-black-100 '
 onChange={(date) => {
  setStartDate(date as SetStateAction<Date>)
 }}
 showYearPicker
 dateFormat='yyyy'
 yearItemNumber={20}
/>

I want to create a calendar like this.

The Issue is I don't know how to add Apply and Cancel button in It. I have tried multiple solutions, But failed to get desired solution.

Through this block of code of I got this.

Kindly help me to add Button in react-datepicker.

import DatePicker from 'react-datepicker'
import 'react-datepicker/dist/react-datepicker.css'
const [startDate, setStartDate] = useState(new Date())

<DatePicker
 selected={startDate}
 className='w-[210px] p-3 text-sm font-[Inter-Regular] outline-none text-black-100 '
 onChange={(date) => {
  setStartDate(date as SetStateAction<Date>)
 }}
 showYearPicker
 dateFormat='yyyy'
 yearItemNumber={20}
/>
Share Improve this question edited Dec 31, 2022 at 7:37 Mosh Feu 29.4k18 gold badges93 silver badges141 bronze badges asked Dec 28, 2022 at 8:13 Muhammad Farooq UsmanMuhammad Farooq Usman 581 silver badge8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You can pass the buttons to the datepicker widget as children.

Both are closing the modal using the datepicker widget's api.
We have access to the api through a ref we assign to the widget.
The cancel button just set the date to the original[1] date.

const originalDate = new Date(); // or get it as prop

const [startDate, setStartDate] = React.useState(originalDate);
const calRef = React.useRef();

return (
  <DatePicker
    ref={calRef}
    selected={startDate}
    shouldCloseOnSelect={false}
    onChange={(date) => setStartDate(date)}
    showYearPicker
    dateFormat="yyyy"
    yearItemNumber={20}
  >
    <div>
      <button
        onClick={() => {
          setStartDate(originalDate);
          calRef.current.setOpen(false);
        }}
      >
        Cancel
      </button>
      <button
        onClick={() => {
          calRef.current.setOpen(false);
        }}
      >
        Apply
      </button>
    </div>
  </DatePicker>
);

https://stackblitz./edit/react-datepicker-footer-buttons?file=App.tsx


[1] original - in your example it would be today but if the ponent receives it as prop, it can be it too

本文标签: javascriptHow to add Custom Buttons in React Datepicker ModelStack Overflow