I am building a form in React that contains an input
of type "date"
. What is the correct way to handle a backspace/edit to the input? For example, when the state is the date 12/12/1212
, and I press backspace on the input, it reverts to an empty input.
The state is:
{
...,
date: new Date(),
}
The state change handler looks like:
const handleDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.target;
setState({ ... state, date: value });
}
The input is:
<input
type="date"
name="date"
value={DateTime.fromJSDate(newOverride.date).toFormat(
"yyyy-MM-dd",
)}
onChange={handleNewInputChange}
/>
In essence, I want to be able to delete/edit the date, without clearing the whole thing and starting again. How can this be achieved?
2
Answers
In order to handle the format error, you need to pass back the exact edit value instead of a parsed one back to the input value.
I used moment for parsing if a date string is in a valid format, display input in red background if not valid, hope you get the idea.
When you use type="date", the browser expects the input value to be in the format "YYYY-MM-DD".If the provided value doesn’t match this format, it defaults to an empty string.
By applying this code, when users press backspace or edit the date, the handleDateChange function will correctly convert the input value to a Date object and update the state accordingly and allowing users to modify the date without clearing the entire input.