How to implement two way data binding in react

How to implement two way data binding in react

In this post we will give you information about How to implement two way data binding in react. Hear we will give you detail about How to implement two way data binding in reactAnd how to use it also give you demo for it if it is necessary.

we are going to learn about two-way data binding in react apps with the help of 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.

Let’s implement the two way binding in react.

class UserInput extends React<span>.Component{  state = {      name:"onlinecode"  }  <span>handleChange = (e) =&gt;{    this.setState({        name: e.target.value    })  }   render(){    return(      &lt;div&gt;       &lt;h1&gt;{this.state.name}&lt;/h1&gt;       &lt;input type="text"         onChange={this.handleChange}         value={this.state.name} /&gt;      &lt;/div&gt;      )   }}

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 this.state.name.so that the value attribute is always synced with this.state.name 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 this.state.name 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.

Two way data binding in React hooks

App.js
import React,{useState} "react";function App(){   const [name,setName] = useState('');  const handleChange = (e)=&gt;{     setName(e.target.value);  } return (   &lt;div&gt;     &lt;input onChange={handleChange} value={name} /&gt;     &lt;h1&gt;{name}&lt;/h1&gt;   &lt;/div&gt; )}export default App;

Hope this code and post will helped you for implement How to implement two way data binding in react. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US