-3

I'm working on a React form where I need to handle a Date of Birth field using an <input type="date">. I want the field to accept dates in the YYYY-MM-DD format, both for displaying the date and for storing it in the state.

When I enter a date manually, the input resets. And when I select a date from the calendar, it doesn't accept the input.

Here’s some part of my code:

import React, { ChangeEvent } from 'react';

const RegisterForm: React.FC<RegisterFormProps> = ({
  dateOfBirth,
  setDateOfBirth,
  isValidAge,
}) => {
  // Handle changes in date input
  const handleDateChange = (e: ChangeEvent<HTMLInputElement>) => {
    const inputDate = e.target.value; // This will be in the format YYYY-MM-DD
    setDateOfBirth(inputDate); // Update the state with the YYYY-MM-DD format
  };

  return (
    <form className="form">
      <div className="form-group">
        <label>Date of Birth</label>
        <div className="input-container">
          <Calendar size={18} className="input-icon" />
          <input
            type="date"
            value={dateOfBirth}  // Directly bind the state in YYYY-MM-DD format
            onChange={handleDateChange}  // Update the state when the user selects a date
            className="input"
            required
          />
        </div>
        {dateOfBirth && !isValidAge && (
          <p className="age-error">You must be at least 15 years old to register</p>
        )}
      </div>
    </form>
  );
};

export default RegisterForm;
2
  • can you show us where the state is being handled in the parent component? both the setter and value?
    – sparkJ
    Commented Apr 16 at 20:02
  • i have solved it in the parent component i am passing blank statement thats why it is not accepting any values <RegisterForm handleSubmit={handleSubmit} dateOfBirth={dateOfBirth} while earlier i am passing dateOfBirth={''} />
    – Kamran
    Commented Apr 17 at 8:17

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.