How to pass values to the onClick function in React
We may need to pass additional parameters into the method when we are binding the event handler in React. So in this article, we will show you how to pass the values in the onClick function in React. In other words, we can tell how to pass events and parameters together in function.
Checkout more articles on ReactJS
Ways to pass values to the onClick function in React
1. Bind method parameters
During the binding of the method, we’ll send the parameters here.
ES5:
1 2 3 4 5 | handleChange(param) { // The parameter you gave to the function is called param. return function (e) { // e stands for the returned event object. }; } |
ES6:
1 2 3 4 | handleChange = param => e => { // param is the argument you passed to the function // e stands for the returned event object. }; |
1 2 3 4 | <input type="text" onChange={this.handleChange("abc")} /> |
2. Using inline Arrow method
Using the inline arrow method, we can pass the event and parameters together in a single function.
1 2 3 4 | handleChange = (e, param) => { // param is the argument you passed to the function // e stands for the returned event object. }; |
1 2 3 4 | <input type="text" onChange={e => this.handleChange(e, "abc")} /> |
3. Pass values through data attributes
The custom data
attribute, which is accessible in React 16 and later versions, can be used instead of inline functions.
1 2 3 4 5 6 | handleChange = e => { const value1 = e.currentTarget.getAttribute("data-val1") const value2 = e.currentTarget.getAttribute("data-val2") console.log("Value 1: ", value1); console.log("Value 2: ", value2); }; |
1 2 3 4 5 6 | <input type="text" data-val1="a" data-val2="b" onChange={this.handleChange} /> |
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂