This website collects cookies to deliver better user experience
How to combine event methods in one in React.js?
How to combine event methods in one in React.js?
Consider you have multiple buttons having several handleClick methods as below:
<buttononClick={handleClick1}>Lorem Ipsum 1</button><buttononClick={handleClick2}>Lorem Ipsum 2</button><buttononClick={handleClick3}>Lorem Ipsum 3</button>...
Thus, what's the problem?! You may have faced it! Consider if you have 100 buttons, you should declare 100 handleClick methods!
Let me show you a simple and elegant way for the problem above.
Use name Attribute
Due to w3schools.com defintion:
the name attribute specifies a name for an HTML element and can be used to reference the element in JavaScript.
Therefore first, I rewrite the code above and two important changes will be in your sights:
One method has been declared for onClick events called handleClick
I've used name attribute along with different values
<buttononClick={handleClick}name="LI1">Lorem Ipsum 1</button><buttononClick={handleClick}name="LI2">Lorem Ipsum 2</button><buttononClick={handleClick}name="LI3">Lorem Ipsum 3</button>...