Skip to content

Instantly share code, notes, and snippets.

@jazlalli
Last active December 22, 2016 10:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jazlalli/fdee443405680f96d19211daa15d1d38 to your computer and use it in GitHub Desktop.
Save jazlalli/fdee443405680f96d19211daa15d1d38 to your computer and use it in GitHub Desktop.
What is the "ideal" way to pass data to a callback prop? An inline function callback which invokes the prop? Or use prop as is and attach data to the event object?
// inline event handler which invokes callback prop
const UsingAnInlineFunction = ({
itemId,
itemName,
itemCount,
onClick
}) => (
<div onClick={() => onClick(itemId)}>
<span>{`${itemCount}x ${itemName}`}</span>
</div>
);
// pass callback prop "as is" and send event data as data attrs
const UsingADataAttribute = ({
itemId,
itemName,
itemCount,
onClick
}) => (
<div onClick={onClick} data-item-id={itemId}>
<span>{`${itemCount}x ${itemName}`}</span>
</div>
);
class ParentComponent extends React.Component {
constructor(props) {
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// I need itemId here, how best to receive it?
}
render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>
<UsingAnInlineFunction
itemId={item.id}
itemName={item.name}
itemCount={item.quantity}
onClick={this.handleClick}
/>
<UsingADataAttribute
itemId={item.id}
itemName={item.name}
itemCount={item.quantity}
onClick={this.handleClick}
/>
</li>
))}
</ul>
);
}
}
@jazlalli
Copy link
Author

jazlalli commented Nov 3, 2016

Having posted this on twitter.com, got a number of further suggestions which I'll list below

constructor(props) {
  super(props);
  this.handleClick = this.handleClick.bind(this);
}

handleClick(item) {
  return (evt) => {
    // we have item here
  }
}

render() {
  return (
    <
      ....
      ....    
      onClick={this.handleClick(item)}
      ....
    />
  );
}

@jazlalli
Copy link
Author

jazlalli commented Nov 3, 2016

We can go one better and remove the .bind from the constructor a la

handleClick = item => evt => {
  // we have item here
}

render() {
  return (
    <
      ....
      ....    
      onClick={this.handleClick(item)}
      ....
    />
  );
}

Thanks to @SanderSpies for this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment