How to pass extra parameters to an onClick event using the ES6 syntax?
For instance:
handleRemove = (e) => { } render() { <button onClick={this.handleRemove}></button> }
I want to pass an id to the handleRemove
function like this:
<button onClick={this.handleRemove(id)}></button>
Passing the event object of react as the second argument. If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.
In React, the onClick handler allows you to call a function and perform an action when an element is clicked. onClick is the cornerstone of any React app. Click on any of the examples below to see code snippets and common uses: Call a Function After Clicking a Button.
You can also pass events like onClick or OnChange Just call an alert method in the childToParent function and pass that function as a prop to the child component. And in the child component, accept the childToParent function as a prop. Then assign it to an onClick event on a button. That's it!
Remember that in onClick={ ... }
, the ...
is a JavaScript expression. So
... onClick={this.handleRemove(id)}
is the same as
var val = this.handleRemove(id); ... onClick={val}
In other words, you call this.handleRemove(id)
immediately, and pass that value to onClick
, which isn't what you want.
Instead, you want to create a new function with one of the arguments already prefilled; essentially, you want the following:
var newFn = function() { var args = Array.prototype.slice.call(arguments); // args[0] contains the event object this.handleRemove.apply(this, [id].concat(args)); } ... onClick={newFn}
There is a way to express this in ES5 JavaScript: Function.prototype.bind
.
... onClick={this.handleRemove.bind(this, id)}
If you use React.createClass
, React automatically binds this
for you on instance methods, and it may complain unless you change it to this.handleRemove.bind(null, id)
.
You can also simply define the function inline; this is made shorter with arrow functions if your environment or transpiler supports them:
... onClick={() => this.handleRemove(id)}
If you need access to the event, you can just pass it along:
... onClick={(evt) => this.handleRemove(id, evt)}
Use the value attribute of the button element to pass the id, as
<button onClick={this.handleRemove} value={id}>Remove</button>
and then in handleRemove, read the value from event as:
handleRemove(event) { ... remove(event.target.value); ... }
This way you avoid creating a new function (when compared to using an arrow function) every time this component is re-rendered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With