JohnRobertPett
JohnRobertPett

Reputation: 1183

Passing both the event and an argument to a handler in React

In React I have created a button, like this:

<Link size="button" onClick={this._handleShareClick.bind(this, this.props.shareID)} href={this.props.URL}>{shareText}</Link>

What I want to do is pass the share ID, but also have access to the regular event object, to allow me to use e.preventDefault();

When I pass to the handler:

_handleShareClick = (e, shareID) => {
    console.log(shareID);
    e.preventDefault();
}

The shareID doesn't console log, and I also get the following error in my console:

Uncaught TypeError: Cannot read property 'preventDefault' of undefined

Is there a reason I can't access both of these things, or is there another approach that I am missing?

Upvotes: 0

Views: 1817

Answers (2)

ben
ben

Reputation: 480

If u need to pass custom parameters, then u can simply pass the parameters to the bind call. The SyntheticEvent will be passed as the second parameter to the handler.

handleClick(param, e) {
  console.log('Parameter', param);
  console.log('Event', e);
}

render() {
  <button onClick={this.handleClick.bind(this, 'Parameter')}></button>
}

Upvotes: 0

Errorpro
Errorpro

Reputation: 2433

You should use:

onClick={(e) => (e.preventDefault(), this._handleShareClick(this.props.shareID))

Upvotes: 2

Related Questions