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

Sometimes, we may run into the ‘A component is changing an uncontrolled input of type text to be controlled’ error when we’re developing React apps.

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

Fix the ‘A component is changing an uncontrolled input of type text to be controlled’ error in React

To fix the ‘A component is changing an uncontrolled input of type text to be controlled’ error in React, we should make sure the value prop of the input is always set to a string.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [value, setValue] = useState();

  return (
    <div>
      <input
        name="name"
        value={value ?? ""}
        onChange={(e) => setValue(e.target.value)}
      />
    </div>
  );
}

to create the value state with the useState hook.

Its initial value is undefined.

Then in the input, we set the value prop to value ?? "" so that the value prop is set to an empty string when the value state is undefined or null.

Now we shouldn’t see this error in the console anymore.

Conclusion

To fix the ‘A component is changing an uncontrolled input of type text to be controlled’ error in React, we should make sure the value prop of the input is always set to a string.