How to pass values to the onClick function in React
π
April 15, 2022
πReactJS
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
- Sticky element on a scroll in React
- How to create tabs in React
- How to validate a radio button in React
- How to set up a proxy in React App
- Login with Google using React
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:
handleChange(param) { // The parameter you gave to the function is called param.
return function (e) { // e stands for the returned event object.
};
}
ES6:
handleChange = param => e => {
// param is the argument you passed to the function
// e stands for the returned event object.
};
<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.
handleChange = (e, param) => {
// param is the argument you passed to the function
// e stands for the returned event object.
};
<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.
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);
};
<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..!! π