Reputation: 111
I am using material-UI datepicker which i followed the procedure but on event handler the date is not changing but the initial value is working fine which i give in useState
. I want my datepicker to work smooth when i want to select my desire date. The example of Datepicker is also in the link
https://material-ui.com/components/pickers/#date-time-pickers https://codesandbox.io/s/z9k3z
import {
KeyboardDatePicker,
MuiPickersUtilsProvider,
} from "@material-ui/pickers";
import DateFnsUtils from "@date-io/date-fns";
import React, { useState } from "react";
function AddCar() {
const [date, setDate] = useState(new Date());
const addCar = (e) => {
e.preventDefault();
console.log(date.toLocaleDateString());
setDate(new Date());
};
return (
<div className="addCar">
<div>
<form className="addCar__form" onSubmit={addCar}>
{/* Date */}
<div className="addCar__mainForm row ">
<div className="col-lg-3 col-md-6 col-sm-12 my-2">
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
disableToolbar
variant="inline"
format="MM-dd-yyyy"
margin="normal"
label="Select Date"
value={date}
onChange={(e) => setDate(date)}
KeyboardButtonProps={{
"aria-label": "change date",
}}
/>
</MuiPickersUtilsProvider>
</div>
</div>
<button type="submit" className="btn btn-success">
ADD CAR
</button>
</form>
</div>
</div>
);
}
export default AddCar;
Upvotes: 1
Views: 1834
Reputation: 873
change this line
onChange={(e) => setDate(date)}
to
onChange={setDate}
Codesandbox: https://codesandbox.io/s/material-demo-forked-siueb?file=/addCar.js:939-957
Upvotes: 1
Reputation: 381
You need to set the value like
onChange={(e) => setDate(e)}
Also, You don't need to set the state like this:
const [date, setDate] = useState(new Date());
Upvotes: 0
Reputation: 687
You keep setting the same date from state.
const [date, setDate] = useState(new Date());
// ...
onChange={(e) => setDate(date)}
It should be:
onChange={(e) => setDate(e)}
The first parameter in DatePicker's onChange callback is the new date you've just input.
Upvotes: 1