I want to display person's email in the alert window. But, I do not know how to pass email as arguments to displayAlert method. Also, it wont let me use either. So, I have to assign displayAlert methos to a variable and use it in onClick. I do not know why it wont let me call it directly.
class People extends React.Component{ render (){ var handleClick = this.displayAlert; var items = this.props.items.map(function(item) { return( <ul key = {item.id}> <li> <button onClick= {handleClick}>{item.lastName + ', ' + item.firstName}</button> </li> </ul> ) }); return (<div>{items}</div>); } displayAlert (){ alert('Hi'); } } class PersonList extends React.Component{ render () { return ( <div> <People items={this.props.people}/> /* People is an array of people*/ </div> ); } }
Asked
Active
Viewed 8.9k times
45

user3528213
- 1,415
- 3
- 15
- 18
2 Answers
83
The ES6 way:
Using arrow functions =>
const items = this.props.items.map((item) => (
<ul key={item.id}>
<li>
<button onClick={() => this.displayAlert(item.email)}>
{item.lastName + ', ' + item.firstName}
</button>
</li>
</ul>
));
onClick
the anonymous function is called and executes this.displayAlert(item.email)
The ES5 way:
You could do this using .bind
and passing the parameter in there.
You should also pass this
or use bind to keep the proper context on your .map
function:
var items = this.props.items.map(function(item) {
return (
<ul key={item.id}>
<li>
<button onClick={this.displayAlert.bind(this, item.email)}>
{item.lastName + ', ' + item.firstName}
</button>
</li>
</ul>
);
}, this);
Shown in the example here: React - Communicate Between Components

Austin Greco
- 32,997
- 6
- 55
- 59
-
Please do not create functions within component `props`. See: https://stackoverflow.com/a/36677798/434697 – Kayote Jun 29 '18 at 14:45
-
Using an arrow function you're creating a new function each time, which has performance effects – Hernán Albertario Sep 08 '20 at 13:49
4
Using arrow function and babel plugin "transform-class-properties"
class People extends React.Component {
render() {
return (
<ul>
{ this.props.items.map( (item) => (
<li key={item.id}>
<button onClick={this.displayAlert(item)}>
{item.lastName + ', ' + item.firstName}
</button>
</li>
))}
</ul>
)
}
displayAlert = (item) => (event) => {
// you can access the item object and the event object
alert('Hi');
}
}

miguel savignano
- 1,109
- 13
- 9
-
What if I want to add to pass another object let say a string along with item? – Siddharth Sachdeva Dec 29 '17 at 02:13