2
votes

I'm using some inputs from Material-Ui. I'm loading the values of these inputs from an API. If the values aren't there, then the user has to type them.

I'm using Hooks and the initial state is: const [bankDetails, setBankDetails] = useState({});

My inputs are configured like this:

                <TextField
                  id="outlined-bank-name"
                  label={t("Bank name")}
                  placeholder={t("Type bank name")}
                  margin="normal"
                  variant="outlined"
                  name="BankName"
                  type="text"
                  value={bankDetails.bankName}
                  onChange={e =>
                    setBankDetails({
                      ...bankDetails,
                      bankName: e.target.value
                    })
                  }
                />

This works fine, however everytime I type something a warning shows:

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

I don't know the reason, because I defined value and onChange props.

What's the best way to solve this problem?

1

1 Answers

1
votes

you are getting this warning because you used:

const [bankDetails, setBankDetails] = useState({});

bankDetails as blank object so during first rendering bankDetails.bankName will be undefined, and input field will get value as:

value={undefined}

modify your hooks like this:

const [bankDetails, setBankDetails] = useState({bankName: ''});