Search code examples
reactjsmaterial-uireact-componentcontrolled-component

Warning: A component is changing an uncontrolled input to be controlled. Minimum working example


When selecting an item, the following warning is raised:

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.

Minimum Working Example

import React, {useState} from "react";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";


export default function Inputs() {
  //const [gender, setGender] = useState("");

  return (
    <TextField select
                //onChange={e => setGender(e.target?.value)}
            >
        <MenuItem key={"a"} value={"a"}>a</MenuItem>
    </TextField>
  );
}

See the problem: Gif

Try it out yourself: Codesandbox.io


Solution

  • After adding value to TextField error disappears:

    import React, { useState } from "react";
    import MenuItem from "@mui/material/MenuItem";
    import TextField from "@mui/material/TextField";
    
    export default function Inputs() {
      //const [gender, setGender] = useState("");
      const [data, setData] = useState("");
    
      return (
        <TextField
          select
          value={data}
          onChange={(e) => setData(e.target.value)}
        >
          <MenuItem key={"a"} value={"a"}>
            a
          </MenuItem>
        </TextField>
      );
    }
    

    Seems like TextField started in uncontrolled mode.