'React DatePicker Not showing the selected date in useState
I have a code that should show the calendar so that user can pick the date : Problem is the useState is not picking the selected date.
Please help me. Below is my code:
import 'react-modern-calendar-datepicker/lib/DatePicker.css';
import DatePicker from 'react-modern-calendar-datepicker';
export default function PostCreateForm(props) {
const [startDate, setStartDate] = useState(new Date());
const handleSubmit = (e) => {
e.preventDefault();
console.log(startDate); // I cannot see the date I selected from the calender
};
return (
<form className="w-100 px-5">
<h1 className="mt-5">Create A New Project</h1>
<div className="mt-4">
<label className="h3 form-label">Project Due Date</label>
<div>
<DatePickern selected={startDate} onChange={date => setStartDate(date)} />
</div>
</div>
<button onClick={handleSubmit} className="btn btn-dark btn-lg w-100 mt-5">Submit</button>
</form>
);
}
Solution 1:[1]
You need to use the value
prop. See the docs for a complete list of available props.
For example, here is a DatePicker
initialized with today's date as the default value:
const [date, setDate] = useState(new Date())
<DatePicker
label="Basic example"
value={date}
onChange={(newValue) => setDate(newValue)}
renderInput={(params) => <TextField {...params} />} />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | pez |