Reputation: 2609
Here is the codesandbox.
I want to create a DateOnly
component that I can use with ease throughout my projects.
And Material-UI complains that:
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components
And here's how it shows the selected date:
I know that controlled input means that you bind both value={value}
and onChange={(newValue) => setValue(newValue);}
.
And here's my return value:
return (
<div>
<KeyboardDatePicker
error={isValid() ? false : true}
id={id}
label={placeholder}
format="MM/dd/yyyy"
value={currentValue}
onChange={(date) => {
setCurrentValue(date);
}}
KeyboardButtonProps={{
"aria-label": "Change " + placeholder
}}
fullWidth
/>
</div>
);
But I don't know why this date field fails to recognize that.
How can I fix this?
Upvotes: 2
Views: 1096
Reputation: 81743
Change this code:
const [currentValue, setCurrentValue] = useState(
new Date(value) || new Date()
);
To:
const [currentValue, setCurrentValue] = useState(
value ? new Date(value) : new Date()
);
new Date(undefined)
is an invalid date (because your component doesn't initialize value
prop). When you pass invalid date value to the picker component, it can't register so it thinks you're using uncontrolled mode and unexpected result happens.
Upvotes: 2