Search code examples
javascriptreactjsreact-datepicker

How to add Custom Buttons in React Datepicker Model


I want to create a calendar like this.

year sate picker

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.

designed Calendar

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}
/>

Solution

  • 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.com/edit/react-datepicker-footer-buttons?file=App.tsx


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