Issue
const [country, set_country] = useState();
<Autocomplete
autoHighlight={true} //needed
autoSelect={true}
id="geo-select-country"
options={all_country}
value={country} // culprit that causes red warning
onChange={(event, selected_country) => {
set_country(selected_country);
}}
classes={autocomplete_classes}
renderInput={(params) => (
<TextField {...params} label={"Country"} margin="none" focused />
)}
/>
warning message:
index.js:1 MUI: A component is changing the uncontrolled value state of Autocomplete to be controlled.
Elements should not switch from uncontrolled to controlled (or vice versa).
Decide between using a controlled or uncontrolled Autocomplete element for the lifetime of the component.
The nature of the state is determined during the first render. It's considered controlled if the value is not `undefined`.
The AutoComplete modifies the useState
, but the value of the useState
modifies the AutoComplete
.
Is this not correct?
Solution
It's because your country value is undefined
in first render, Just provide initial value for your country state, like this:
const [country, set_country] = React.useState('');
or
const [country, set_country] = React.useState(null);
When you don't provide value
attribute on AutoComplete
or when you set value
attribute with undefined
, MaterialUI considers AutoComplete
as uncontrolled component, it means that actually MaterialUI considers you haven't provide any state by yourself to update the value
of AutoComplete
, but if you provide value
on AutoComplete
, materialUI considers AutoComplete
as controlled component, it means that materialUI knows that you have defined some state value to controll the value of AutoComplete
.
In your example, in the first render your country
is undefined
, so MaterialUI considers AutoComplete
as uncotrolled component, and tries to controll the value of AutoComplete
by ownself, but in the next renders, your country is not undefined
, so material has to change some inner decisions and this cause the warning it throws.
Answered By - Saeed Shamloo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.