Home > Web Front-end > JS Tutorial > body text

USING JAVASCRIPT CLOSURES IN REACT

WBOY
Release: 2024-07-17 18:23:19
Original
844 people have browsed it

USING JAVASCRIPT CLOSURES IN REACT

A Closure is a Javascript feature where a function,enclosed inside another function (outer function), is returned and invoked outside of the outer function.

A closure is formed when the inner function maintains access to variable outside its scope aka lexical scope; access to variables and arguments of the outer function even after the outer has executed.

Let's create a tax calculator closure function to calculate taxes for alcoholic and non-alcoholic drinks based on their tax rates.

const taxCalculator = (vat ) => {
  return function taxableAmount (amount) {
    const tax = amount * vat / 100;
    return tax
  }
}

//alcoholic drinks have their on VAT, lets say 16%
const alcoholTax = taxCalculator(16)
const alcoholA = alcoholTax(1200) // an Alcohol that costs 1200
const alcoholB=alcoholTax(800) // an Alcohol that costs 800

//non-alcoholic have their own VAT, let say 12%

const nonAlcoholTax = taxCalculator(12);
const water = nonAlcoholTax(500)
const Juice=nonAlcoholTax(300)
Copy after login

As you can see, each drink will always remember their tax rate based on the whether it is alcoholic drink or non-alcoholic i.e the returned function is invoked outside of taxCalculator and is able to retrieve the value vat parameter even though the main function taxCalculator had been executed.

In react js, JavaScript UI library, event handlers are declared inline on the JSX as such.

<button  onClick={handleClick}>Click me</button> 
Copy after login

If the event handler has an argument, it will then be invoked inside a function as such.

function ActionButtons(){
const actions = ["Create", "Edit", "Delete"]
const handleAction = (action) => {
    switch (action) {
      case actions[0]:
        //do something
        break;
      case actions[1]:
        //do something
        break;
      case actions[2]:
        //do something
        break;

      default:
        // do nothing
        break;
    }
  }
return (
<div className="flex flex-col md:flex-row w-full p-4 gap-4 ">
  { actions.map(action => 
<button 
className="w-full md:w-60" 
  style={{
            backgroundColor: "palevioletred",
            color: "white",
            outline: "none",
          }}
onClick={()=>handleAction(action)}>{action}</button>)}
  </div>)
}
Copy after login

Note the handleAction is encapsulated by an arrow function when assigning it to the onclick event handler.

With closure we can simply call handleAction with a action argument then return an inner function that grabs the action argument and performs the rest of the actions like so.

function ActionButtons() {
  const actions = ["Create", "Edit", "Delete"];
  const handleAction = (action) => {
    return function () {
      console.log(` ${action} Action button clicked`);
      switch (action) {
        case actions[0]:
          //do something
          break;
        case actions[1]:
          //do something
          break;
        case actions[2]:
          //do something
          break;

        default:
          // do nothing
          break;
      }
    };
  };
  return (
    <div className="flex flex-col md:flex-row  w-full p-4 gap-4 justify-between">
      {actions.map((action) => (
        <button 
className="w-full md:w-60"
  style={{
            backgroundColor: "palevioletred",
            color: "white",
            outline: "none",
          }}
 onClick={handleAction(action)}>
          {action}
        </button>
      ))}
    </div>
  );
}

Copy after login

Notice how we invoke the handleAction directly on the OnClick event? also notice we have refactored the handleAction function so that it returns a function performing the necessary actions wity a switch ?

The handleAction is invoked when the component mounts, a closure occurs when the function returned by handleAction grabs and holds onto to the value of the argument on handleAction even though it (handleAction) executed during the first render.
It is a neat way of handling events in Javascript.what do you think?

The above is the detailed content of USING JAVASCRIPT CLOSURES IN REACT. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!