What should I do to clear date input?, I have button that if the user clicked, it will clear the date.
const [startdate, setStartDate] = useState();
const [endDate, setEndDate] = useState();
const onChangedate = (e) => {
let startDate = convertDate(e.startDate);
let endDate = convertDate(e.endDate);
setStartDate(startDate);
setEndDate(endDate);
};
const handleClearfilter = () =>{
setStartDate("");
setEndDate("");
}
<DateRangePickerComponent placeholder='Select a range' change={onChangedate}
style={{paddingTop: 10, fontSize: 16}}
/>
<Button
onClick={handleClearfilter}
>
Clear All
</Button>
CodePudding user response:
I suggest using a React key to "reset" the uncontrolled input. When the React key changes React will throw away the old version and mount a new "instance".
See fully uncontrolled component with a key for example and deeper explanation.
const [key, setKey] = useState(false);
...
const handleClearfilter = () =>{
setStartDate("");
setEndDate("");
setKey(k => !k); // toggle React key value
}
<DateRangePickerComponent
key={key} // <-- attach React key
placeholder='Select a range'
change={onChangedate}
style={{paddingTop: 10, fontSize: 16}}
/>
CodePudding user response:
If you want to control the component, you have to feed in the values yourself. The docs show that you require two date values since it is a data range input.
const [startdate, setStartDate] = useState();
const [endDate, setEndDate] = useState();
const onChangedate = (e) => {
let startDate = convertDate(e.startDate);
let endDate = convertDate(e.endDate);
setStartDate(startDate);
setEndDate(endDate);
};
const handleClearfilter = () =>{
setStartDate("");
setEndDate("");
}
<DateRangePickerComponent placeholder='Select a range' change={onChangedate} startDate={startDate} endDate={endDate}
style={{paddingTop: 10, fontSize: 16}}
/>
<Button
onClick={handleClearfilter}
>
Clear All
</Button>