How to implement two way data binding in react

How to implement two way data binding in react

In this tutorial, we are going to learn about two-way data binding in react apps with examples.

What is two way data binding?

Two data binding means

  • The data we changed in the view has updated the state.
  • The data in the state has updated the view.

react two way data binding

Let’s implement the two way binding in react.

class UserInput extends React.Component{

  state = {
      name:"reactgo"  }

  handleChange = (e) =>{    this.setState({        name:    })  }
       <input type="text"         onChange={this.handleChange}         value={} />      </div>

Two data binding demo

In the above code, we have attached an onChange event handler to the input element and also value attribute is connected to the that the value attribute is always synced with property.

Whenever the user changes an input in the view it triggers the onChange event handler then it calls the this.setState method and updates the property value at final the UserInput component is re-rendered with the updated changes.

This is also called controlled component because the value of an input element is controlled by the react.