skip to Main Content

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


  1. 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.

    const Datepicker = () => {
      const [state, set] = useState();
    
      const parsed = moment(state, "YYYY-MM-DD", true);
      const error = !parsed.isValid();
    
      return (
        <input
          type="date"
          name="date"
          value={state}
          onChange={(e) => set(e.target.value)}
          style={{ backgroundColor: error ? "red" : undefined }}
        />
      );
    };
    
    Login or Signup to reply.
  2. 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.

    import { DateTime } from "luxon";
    
    const handleDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
      const { name, value } = event.target;
    
      const dateObject = DateTime.fromFormat(value, "yyyy-MM-dd").toJSDate();
    
      setState({ ...state, date: dateObject });
    };
    
    <input
      type="date"
      name="date"
      value={DateTime.fromJSDate(state.date).toFormat("yyyy-MM-dd")}
      onChange={handleDateChange}
    />
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search