Categories
React Answers

How to fix ‘A component is changing an uncontrolled input of type text to be controlled’ error in React?

Spread the love

Sometimes, we want to fix ‘A component is changing an uncontrolled input of type text to be controlled’ error in React.

In this article, we’ll look at how to fix ‘A component is changing an uncontrolled input of type text to be controlled’ error in React.

How to fix ‘A component is changing an uncontrolled input of type text to be controlled’ error in React?

To fix ‘A component is changing an uncontrolled input of type text to be controlled’ error in React, we should make sure the value prop is always set to something other than null or undefined.

For instance, we write

<input
  id={myId}
  name={myName}
  type="checkbox"
  value={myStateValue ?? ""}
  checked={someBoolean ? someBoolean : false}
/>;

to set the value prop to myStateValue ?? "".

If myStateValue is null or undefined, then value is set to an empty string.

Then the input always stays a controlled input.

Conclusion

To fix ‘A component is changing an uncontrolled input of type text to be controlled’ error in React, we should make sure the value prop is always set to something other than null or undefined.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *