Author -  Sai gowtham

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 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.

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: e.target.value    })  }

   render(){
    return(
      <div>
       <h1>{this.state.name}</h1>       <input type="text"         onChange={this.handleChange}         value={this.state.name} />
      </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 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)=>{
     setName(e.target.value);  }

 return (
   <div>
     <input onChange={handleChange} value={name} />     <h1>{name}</h1>
   </div>
 )
}

export default App;

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY