How to Add Two-Way Binding in React

How to Add Two-Way Binding in React with Examples:

In this article, I am going to discuss How to Add Two-Way Binding in React with Examples. Please read our previous article where we discussed Handling Form Submission in React.

Adding Two-Way Binding in React:

In our previous article, we have seen how to print the values of entered data on the console. In this article, we will see how can we clear those inputs after the submission of the form. Well, that’s part of the reason why we wanted to use the state for storing the entered values. we could also use global variables outside of the component function. But by using the state, we have an advantage. Now, we can implement something which is called two-way binding

Two-way binding means that the inputs that we listen to change, but we can also pass a new value back into the input. So that we can reset or change the input programmatically. And how do we do that? Well, it’s very simple. All we have to do is add the value attribute in the input field, which is a default attribute, to the input element.

How to Add Two-Way Binding in React with Examples

This will set the internal value property, which every input element has. And we can set it to a new value. And in the input field of title, we will bind the value to enteredTitle. So, this is two-way binding. Because now we don’t just listen to changes in the input to update our state, but we also feed the state back into the input so that when we change the state, we also change the input. This might sound like an infinite loop, but it isn’t.

So we won’t have a problem there. But the advantage is that when the form is submitted, we can call setEnteredTitle and set this back to an empty string which also was our initial state,

How to Add Two-Way Binding in React with Examples

And by doing that, we override what the user entered after the form was submitted and therefore, cleared the input. And we can do this for all inputs. We can set the entered amount to an empty string and set the entered date to an empty string,

How to Add Two-Way Binding in React with Examples

And now just add the value prop to all these inputs as,

How to Add Two-Way Binding in React with Examples

Now, if we save this and reload the page, we can enter something here as it seems,

How to Add Two-Way Binding in React with Examples

but if we click on ‘Add Expense’,

How to Add Two-Way Binding in React with Examples

It’s all cleared again as it was initially. And we still have our data collected and stored in the object. So, this is a new behavior, but more importantly, this is also another key concept in React. Two-way binding is very useful when you’re working with forms because it allows you to gather user input but then also change it.

Full Code of ExpenseForm.js:
import React, { useState } from "react";

import "./ExpenseForm.css";

const ExpenseForm = () => {
  const [enteredTitle, setEnteredTitle] = useState("");
  const [enteredAmount, setEnteredAmount] = useState("");
  const [enteredDate, setEnteredDate] = useState("");

  // const[userInput, setUserInput] = useState({
  //   enteredTitle: '',
  //   enteredAmount: '',
  //   enteredDate: ''
  // });

  const titleChangeHandler = (event) => {
    setEnteredTitle(event.target.value);

    // setUserInput({
    //   ...userInput,
    //   enteredTitle: event.target.value
    // })

    // setUserInput((prevState) => {
    //   return {...prevState, enteredTitle: event.target.value};
    // });
  };

  const amountChangeHandler = (event) => {
    setEnteredAmount(event.target.value);

    // setUserInput({
    //   ...userInput,
    //   enteredAmount: event.target.value
    // })

    // setUserInput((prevState) => {
    //   return {...prevState, enteredAmount: event.target.value};
    // });
  };

  const dateChangeHandler = (event) => {
    setEnteredDate(event.target.value);

    // setUserInput({
    //   ...userInput,
    //   enteredDate: event.target.value
    // })

    // setUserInput((prevState) => {
    //   return {...prevState, enteredDate: event.target.value};
    // });
  };

  // const inputChangeHanlder = (identifier, value) => {
  //   if (identifier == "title") {
  //     setEnteredTitle(value);
  //   } else if (identifier == "date") {
  //     setEnteredDate(value);
  //   } else {
  //     setEnteredAmount(value);
  //   }
  // };

  const submitHandler = (event) => {
    event.preventDefault();

    const expenseData = {
      title: enteredTitle,
      amount: enteredAmount,
      date: new Date(enteredDate),
    };

    console.log(expenseData);
    setEnteredTitle('');
    setEnteredAmount('');
    setEnteredDate('');
  };

  return (
    <form onSubmit={submitHandler}>
      <div className="new-expense__controls">
        <div className="new-expense__control">
          <label>Title</label>
          <input
            type="text"
            value={enteredTitle}
            onChange={titleChangeHandler}
          />
        </div>
        <div className="new-expense__control">
          <label>Amount</label>
          <input
            type="number"
            value={enteredAmount}
            onChange={amountChangeHandler}
            min="0.01"
            step="0.01"
          />
        </div>
        <div className="new-expense__control">
          <label>Date</label>
          <input
            type="date"
            value={enteredDate}
            onChange={dateChangeHandler}
            min="2023-06-25"
            max="2025-12-31"
          />
        </div>
      </div>
      <div className="new-expense__actions">
        <button type="submit">Add Expense</button>
      </div>
    </form>
  );
};

export default ExpenseForm;

In the next article, I am going to discuss Child-to-Parent Component Communication in React (Bottom-up) with Examples. Here, in this article, I try to explain How to Add Two-Way Binding in React with Examples. I hope you enjoy this Two-Way Binding in React article.

Leave a Reply

Your email address will not be published. Required fields are marked *