Reputation: 379
I'm learning React and currently dealing with Material-UI Date Picker but I'm unable to change the date from the calendar.
The current state I'm using
const [state, setState] = React.useState({ ...newTripStateData })
I have all state data in that ojbect (newTripStateData) but when I try to access and change the departureDate which is equal to(new Date) using the below function; it's not changing. What am I doing wrong?
const handleDateChange = (date) => {
state.departureDate = date;
setState(state.departureDate)
}
Date Picker
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
className={styles.inputs}
disableToolbar
inputVariant="outlined"
format="MM-dd-yyyy"
error={state.departureDateErrorStatus}
margin="normal"
id="date-picker-inline-1"
label="Departure Date"
selected={state.departureDate}
onChange={handleDateChange}
KeyboardButtonProps={{
'aria-label': 'change date'
}}
/>
<FormHelperText
error={state.departureDateErrorStatus}
className={styles.helper_text_error}
>
{state.departureDateError}
</FormHelperText>
</MuiPickersUtilsProvider>
Material UI Error in the Chrome dev tools
Material-UI: a component is changing the controlled value state of SelectInput to be uncontrolled.
Thanks in advance.
Upvotes: 0
Views: 3866
Reputation: 14355
There is no selected
prop according to the docs.
Change selected={state.departureDate}
to value={state.departureDate}
. Along with the function updates described in @deadcoder0904's answer:
const handleDateChange = (date) => {
setState({
...state,
departureDate: date
})
}
Upvotes: 1
Reputation: 310
Dont set the state directly, use only the setState method. Also it is better to create a state variable instead of pushing the whole state into one:
...
const [date, setDate] = React.useState()
...
const handleDateChange = (date) => {
setDate(date)
}
See https://reactjs.org/docs/hooks-state.html#tip-using-multiple-state-variables
Upvotes: 0
Reputation: 8683
You can't change state
like state.departureDate = date
. You have to use setState
to change it.
You can directly do:
const handleDateChange = (date) => {
setState({
...state,
departureDate: date
})
}
Upvotes: 2