Last active
December 22, 2016 10:44
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We can go one better and remove the
.bind
from the constructor a laThanks to @SanderSpies for this one.