Creating a Shared Handler Function in React

Creating a Shared Handler Function in React:

In this article, I am going to discuss Creating a Shared Handler Function in React with Examples. Please read our previous article where we discussed Updating State that Depends on the Previous State in React.

Alternative Creating a Shared Handler Function in React:

Now before we’ll dive deeper into state and React events, we want to take a closer look at these change handler functions,

Alternative Creating a Shared Handler Function in React

As shown above, here, we have three change handler functions. One for the title, one for the amount, and one for the date. This makes sense since we have the three-state slices,

Alternative Creating a Shared Handler Function in React

Using this approach is absolutely fine. There’s nothing wrong with having these different change handler functions. But we want to show you an alternative approach you can also consider using.

Creating one Shared Handler Function in React:

Instead of having all these separate change handler functions, we can create one shared change handler function. For that, we have to create a new function with the help of the arrow function that can be named as inputChangeHandler and here we’ll not accept the event argument. But instead, we can accept some ‘identifier’ and ‘value’. You can name this anything. The name is up to you.

Creating one Shared Handler Function in React

The idea is that we can use this single function for all my inputs, for all those onChange events. Then, we can simply identify the different inputs with the help of an ‘identifier’ and update the correct state slice based on the identifier that was passed to this function with the value.

For example, we will check if (identifier == ‘title’), we update the title state by calling setEnteredTitle and passing the value inside it as a parameter. Then, else if (identifier == ‘date’), then, we update the date state by calling setEnteredDate and passing the value. And else we will call setEnteredAmount with the value as a parameter.

Creating one Shared Handler Function in React

So, with that, we’re calling all these state updating functions but now we’re doing this all-in-one shared change handler function. But we can’t use this inputChangeHandler function as an input for onChange. That won’t work. Because as you learned, react will, in the end, call this function for us and will pass an event object to it. So, it will definitely not pass an identifier and value to it. We’re not going to get those data points when React calls this function. But we need them for this function to work correctly.

Now, what we can do to work with this function? Instead of passing a pointer to inputChangeHandler as a value to onChange, we can pass an arrow function to it. A new anonymous arrow function which we create in the onChange prop.

Creating one Shared Handler Function in React

With that, this arrow function will be called by React whenever this input changes. Therefore, this arrow function will receive the event object. And inside the body of this arrow function, we can now manually execute the inputChangeHandler function. We manually execute it by adding parentheses.

Now the body of the arrow function will not be executed when the line of input code is parsed, but instead, the body of the arrow function will only be executed when the arrow function is executed. And that will only be the case when the change event occurs.

Creating one Shared Handler Function in React

Now, we have this wrapper arrow function. We have full control over how the inputChangeHandler will be executed. And therefore, we can now pass our identifier as a first argument and pass the value that changed as the second argument.

For example, ‘title’ as the identifier and pass event.target.value as the second argument. just as before, but now in this arrow function. And with that, we as a developer, control how this function will be called by wrapping it in an arrow function, which is the actual function that’s passed as a value to the onChange prop.

Creating one Shared Handler Function in React

We control how this inner function will be executed when the change event occurs, and we can then use this generic handler function because now we can use the same code function in the onChange prop in the input field of Amount and Date,

Creating one Shared Handler Function in React

So, the function that’s being executed inside the body of the arrow function is always the same. This approach is an alternative to having multiple specialized handler functions. As mentioned, there’s nothing wrong with having specialized or different handler functions, but as an alternative, you could consider using the shared functions. Now let’s shift back to the different handler functions.

Creating one Shared Handler Function in React

So, we have moved back to the code that we had before with the titleChangeHandler amountChangeHandler and dateChangeHandler. You might see the shared handler functions in some React projects. And since it is something, you might want to use yourself in your React projects. So, it was necessary to share the alternative approach with you.

Full Code of ExpenseForm.js File:
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);
  //   }
  // };

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

export default ExpenseForm;

In the next article, I am going to discuss Handling Form Submission in React with Examples. Here, in this article, I try to explain Creating a Shared Handler Function in React with Examples. I hope you enjoy this Creating a Shared Handler Function in React article.

Leave a Reply

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