AMHNewsHub

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

December 15, 2022 By sanxbot00

In React, an uncontrolled input is a form input element where the value is managed by the DOM rather than by React. This means that the value of the input is not controlled by the component, and the component will not be able to update it when the input value changes.

To fix this error, you should convert the uncontrolled input to a controlled input. This can be done by adding a value prop to the input element and a onChange event handler that updates the value of the value prop.

Here is an example of how you might do this:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: ''
    };
  }

  handleChange = (event) => {
    this.setState({inputValue: event.target.value});
  }

  render() {
    return (
      <input type="text" value={this.state.inputValue} onChange={this.handleChange} />
    );
  }
}

In this example, the input is initially uncontrolled, but when the user types in the input, the onChange event handler is called, which updates the inputValue in the component’s state. This causes the input to become controlled, and the value of the input will always be the same as the value in the component’s state.