If you’re coming from Vue or Angular, you might be wondering how to do two-way data binding in React.
No need to worry, because In this article we’ll explore how to implement two-way binding in React. Mostly we will focus on binding input elements’ value to the state.
Two-way binding in React
React provides all necessary tools to implement two way data binding in React. You do need to write a little more code to implement a feature like v-model in React.
First, let’s explain what two-way binding means. Essentially, your input element’s value comes from the state. However, users should be able to change current input. So changes in the input element should be reflected in the state.
For that, we use onChange event handler and value attribute set on input elements in React.
Let’s look at code example:
However, this approach also gives you more freedom and helps by keeping your data consistent. Once you get used to it, doing two-way data binding is not time-consuming or difficult.
Text input fields
Let’s explore how to set up two-way data binding for most common type of input in React.
You need to do the following:
- Create a state variable to hold user inputs.
- Set input element’s value attribute to the state.
- Use onChange event handler to update the state variable every there’s a change in the field.
Let’s look at a code example:
Due to value attribute, input field gets its value from the state.
Then onChange waits for change events. Whenever users enter a new value or delete something from the field, it will accesses most recent input value (e.target.value) and updates state variable.
Note: when you initialize a state value to store a text input, set its default (initial) value to an empty string.
Implementing two-way binding in React works more or less the same for all types of inputs.
In case of <select> elements, you need to change onChange and value attributes on the <select> element itself. Of course, you also need to create a state variable.
With radio buttons, you give users multiple options. Usually they can choose only one option from the group.
For this reason, two-way binding for radio buttons works a little differently in React.
Similar to previous examples, you need to create a state variable to store user inputs.
One difference is in the value of radio inputs. Every radio button’s value is fixed (“yes” and “no”, for example).
You also need to set checked attribute on input to a condition that checks if radio button’s value matches current user input (stored in the state). If condition is true, checked will be set to true, and radio button will be checked.
Here’s an example of how to implement two-way binding in React: