Hello, in this tutorial, we'll go over what does it mean for One-way and Two-way data binding.
Hello, in this tutorial, we'll go over what does it mean for One-way and Two-way data binding.
Setup
Before we get started, we need to setup a few things.
What is One-way and Two-way data binding
One-way binding excercise
import { useState } from 'react';
let [ value, setValue ] = useState("Hello");
<input onChange={}/>
<input onChange={onInputChanged}/>
function onInputChanged(event) {}
Add a console.log statement and print out the event info.
Now when you save the changes and start typing again, the value of the text should reflect whatever you typed in the input.
To recap, the One-way data binding occurred when we created useState and interpolated it in the HTML.
useState ---> <p>{value}</p>
We then created another One-way binding scenario when we added an onChange event to the input and wrote logic to change the value of the useState using it's mutator function.
<input .../> ---> useState ---> <p>{value}</p>
The input is updating the value of the useState so it is flowing in 1 direction.
Two-way binding exercise
In the One-way data binding exercise, we bound the useState with the input.
<input .../> ---> useState
In the One-way data binding exercise, we bound the useState with the input and whenever we typed the data flowed into the useState and changed it's value.
<input .../> < == > useState
Step 1:
Step 3:
Step 4:
Step 5:
Notice how when the button change the text, the text in the input has not changed.
Step 6:
Now when we repeat the steps from 4 and 5, the value of the useState and input should be syncronized.
That is all for One-way and Two-way data binding. As you saw, in One-way, data is changed in one direction. In Two-way data binding, the value can also effect the source that can change its value.