Sometimes, we need to fix the ‘A component is changing a controlled input of type text to be uncontrolled’ error with the React Material UI select component.
In this article, we’ll look at how to fix the ‘A component is changing a controlled input of type text to be uncontrolled’ error with the React Material UI select component.
How to fix the ‘A component is changing a controlled input of type text to be uncontrolled’ error with the React Material UI select component?
To fix the ‘A component is changing a controlled input of type text to be uncontrolled’ error with the React Material UI select component, we can set the default value for the value
prop.
For instance, we write:
import React, { useState } from "react";
import { FormControl, InputLabel, Select, MenuItem } from "@material-ui/core";
export default function App() {
const [age, setAge] = useState();
return (
<div>
<FormControl fullWidth>
<InputLabel>Age</InputLabel>
<Select
value={age ?? 10}
label="Age"
onChange={(e) => setAge(e.target.value)}
>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</div>
);
}
We set the value
prop of the Select
component to the age
state.
And we set the value
to 10 if age
is undefined.
Next, we add the onChange
prop and set it to a function to set the age
state to the selected value.
And we add some MenuItem
s inside the Select
component to add some choices.
Conclusion
To fix the ‘A component is changing a controlled input of type text to be uncontrolled’ error with the React Material UI select component, we can set the default value for the value
prop.