Search code examples
reactjscalendarflatpickr

unable to clear flatpickr selected date on click of cross icon


I am trying to use clear functionality which is available in flatpickr, but facing issue when i am using it in react-flatpickr. My use case is very simple where I have added an svg cross icon and on click of that icon I want to clear the selected date in the flatpickr input field.

const element = document.querySelector("[class=flatpickr-input]")

<>
<img src={calendar} alt="calendar" className={'flat-calendar'} data-testid={'flat-calendar-icon'}/>
    <Flatpickr options={config} value={value && new Date(value)} onChange={(eventValue) => localOnChange(eventValue[0])}/>
<img src={crossFilled} alt="calendar" className={'clear-icon'} onClick={() => element.clear()}/>
<>

I am not sure if I am using it wrong or something I am missing, if anyone can help it would be great. Thanks in advance !!


Solution

  • Got it working using React refs. Created a reference of flatpickr using React refs and the called clear on the flatpickr ref.

    const refComp = useRef(null);
    
    const clearDate = () => {
      refComp.current.flatpickr.clear();
    }
    
    <>
    <img src={calendar} alt="calendar" className={'flat-calendar'} data-testid={'flat-calendar-icon'}/>
        <Flatpickr options={config} value={value && new Date(value)} onChange={(eventValue) => localOnChange(eventValue[0])} ref={refComp}/>
    <img src={crossFilled} alt="calendar" className={'clear-icon'} onClick={clearDate}/>
    <>