21 February 2020

Two way data binding in react


In this Example we can see Two way data binding (Parent to Child and Child to parent) 
  • Create Components folder under src folder
  • Add TwoWayBindingParent.js file and add below Code
import React,{Componentfrom 'react';
import TwoWayBindingChild from './TwoWayBindingChild';

class  TwoWayBindingParent extends Component {
  state={
    Person:[
      {name:'adi',age:29}
    ]
  }

nameChangedEvent=(event)=>{
    this.setState({Person:[
        {name:event.target.value ,age:30}
      ]})
    }


  render(){
  return (
    <div>
        <p>Two Way Binding </p>
      <TwoWayBindingChild 
      name={this.state.Person[0].name} 
      age={this.state.Person[0].age}
      changed={this.nameChangedEvent}/>
    </div>
  );
  }
}

export default TwoWayBindingParent;
  • Add TwoWayBindingChild.js file and add below Code
import React from 'react';

const TwoWayBindingChild =(props)=>{
    return(
        <div>
        <p onClick={props.click}>I'm a {props.name} and i am {props.age} years old!</p>
       <input type="text" onChange={props.changed}></input>
        </div>
    );
}
export default TwoWayBindingChild;
  • Open App.js file and update code as below
import React from 'react';
import './App.css';
import TwoWayBindingParent from './Components/TwoWayBindingParent'

function App() {
  return (
    <div className="App">
     <TwoWayBindingParent/>
    </div>
  );
}

export default App;
Output:

No comments:

Post a Comment