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;