Home > Back-end >  Warning: A component is changing an uncontrolled input to be controlled. Minimum working example
Warning: A component is changing an uncontrolled input to be controlled. Minimum working example

Time:07-11

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

CodePudding user response:

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.

CodePudding user response:

In your sandbox, prior to selecting the option you already receive the following warning:

MUI: You have provided an out-of-range value `undefined` for the select component.
Consider providing a value that matches one of the available options or ''.
The available values are `a`. 

    in SelectInput (created by MuiOutlinedInputInput)
    in MuiOutlinedInputInput (created by InputBase)
    in InputBase (created by OutlinedInput)
    in OutlinedInput (created by Select)
    in Select (created by TextField)
    in TextField (created by Inputs)
    in Inputs 

Though MUI's Select can be used in either a controlled or uncontrolled mode (https://reactjs.org/docs/forms.html#controlled-components), you need to specify the initial value in some fashion. If you want to use the uncontrolled mode, then you should specify defaultValue="". If you want to use the controlled mode, then you would specify value={gender} (along with uncommenting the code for managing the state). Specifying the initial value in one of these two ways avoids the warning that you mentioned in your question.

  • Related