Skip to content

Prop to pass data to event handlers #12169

Closed
@shanimal

Description

@shanimal

This is a feature request

My suggestion is to add a known prop that gets passed through to all handlers as the second parameter. This would eliminate the need for closures, inline binding, inline arrow functions, proxyEvent.target.dataset, etc.

handleClick(proxyEvent, eventData) {
  // do stuff with eventData...
}
<Component eventData={data} onClick={this.handleClick} />

Currently if we need to pass data through an event handler there are several ways...

Create a class method that returns a closure:

clickHandler(eventData) {
  return (proxyEvent) => {
    // do stuff with eventData
  }
}
<Button onClick={clickHandler(eventData)} />

use inline bind or arrow function

clickHandler(eventData, proxyEvent) {
  // do stuff with eventData
}
<Button onClick={this.clickHandler.bind(this, eventData)} />
<Button onClick={(proxyEvent) => clickHandler(eventData, proxyEvent)} />

AND

A not so intuitive alternative is to use proxyEvent.target.dataset

clickHandler(proxyEvent) {
    const eventData = datas
      .find(data => data.get('id') === proxyEvent.target.dataset.button);
    // do stuff with eventData...
}
<Button onClick={clickHandler} data-button={data.get('id')} />

If you pass an object to any data-prop it gets converted to a string. My immutable Map becomes DOMStringMap {button: "Map { "id": "84280bcc-ab3b-45d5-8882-dc74a17da... so I have to pass an ID and use it in the handler to find my data.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions