I have a component with a date picker and a would like to change the value of the date picker in the state, using hooks, and also the date in the date picker itself, so you can select a date, or you can click a button to set a date, like 30 days ago.
this is what I tried so far:
const MyComp = () => {
const [formData, setFormData] = useState({
dateFrom: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
dateTo: new Date()
});
const handleDateClick = interval => {
setFormData({...formData, dateFrom: new Date(Date.now() - interval * 24 * 60 * 60 * 1000)});
setFormData({...formData, dateTo: new Date()});
};
const handleOnChange = e => {
setFormData({...formData, [e.target.name]: e.target.value});
};
return (
<Button onClick={() => handleDateClick(30)} variant="secondary">30 days ago</Button>
<DatePicker
selected={formData.dateFrom}
name="dateFrom"
dateFormat="MMMM d, yyyy"
onChange={value => handleOnChange({target: {name: "dateFrom", value}})}
/>
);
}
clicking the button has no effect, not even displaying any error, the state is not updated and the value in the datepicker does not change? Any idea please?