Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Two-way data binding in React JS

Two-way data binding in React JS

In this chapter, you will learn about two-way data binding in React JS. React JS uses one-way data binding approach and there is no such approach like it follows two data binding approach. Let’s create a component that defines the method changeNameHandler() to change the employee name and display it in the paragraph. Follow the below steps for the same.

Step 1:
Create the file src/Employee/Employee.js if you have it already paste the below code snippet. We have defined the input field with type text and registered the method props.changeName.

import React from 'react';

const employee = (props) => {
return (
        <div>
                <input type='text' onChange={props.changeName}/>
                <h2>Employee Name: {props.name}</h2>
        </div>
    )
}

export default employee;

Steps 2:
Create the file src/App.js if you have it already paste the below code snippet. As we can see in the below example, we have defined the method changeNameHandler, that updated the state of employee name.

import React, {Component} from 'react';
import './App.css';
import Employee from './Employee/Employee'
class App extends Component {
  state = {
    employee : ''
  }

  changeNameHandler = (e) => {
    this.setState({
      employeeName : e.target.value
    })
  }
  render() {
    return (
      <div className="App">
        <h1>Welcome to react JS tutorial</h1>
        <Employee changeName={this.changeNameHandler} name={this.state.employeeName} />
      </div>
    );
  }
}

export default App;

Now go to the browser and hit the URL http://localhost:3000. If you type in the input field, the same value will be updated to employee name.

Two way data binding in React JS

2 thoughts on “Two-way data binding in React JS

  1. What if we need the ability to change the employee name in 5 different components ? Seems to me that using your solution we would have 5 separate changeNameHandler() to keep track of

Comments are closed.