Fellow Stranger Fellow Stranger - 3 months ago 10
React JSX Question

Passing event + arguments in an event handler callback

I can successfully pass an argument from an event handler with the code below.

But I wonder, how would I as well pass the

event
to the function
handleDown
?

class Parent extends React.Component {
handleDown(argumentOne) {
}
render () {
return (
<div>
<Child
handleDown={this.handleDown.bind(this)}
/>
</div>
);
}
}

class Child extends React.Component {
constructor(props) {
super(props);
}
render () {
return (
<div>
<span
onMouseDown={this.props.handleDown.bind(this, 'argumentOne')}
>
Click here
</span>
</div>
);
}
}

Answer

how would I as well pass the event to the function handleDown?

You don't, the event mechanism does, but given the code in the question, handleDown will receive the event as the first argument after the ones you've provided.

So here:

<Child 
    handleDown={this.handleDown.bind(this)}
/>

it would be the first argument to handleDown, and here:

<span
    onMouseDown={this.props.handleDown.bind(this, 'argumentOne')}
>

it would be the second argument to handleDown.

I'd probably modify the first bind call to pass null or something so that you consistently get it as the second argument. But unless React does something special, it will always be the last argument, so you could work from that.