Reputation: 2109
I have just started to work with ReactJS and I can't figure out how I can make onClick events work inside a map function, which renders a few similar elements. When I am not using onClick={this.someMethodName} in the child elements, everything is working fine, so I am guessing the 'this' keyword no longer refers to the parent.
Here is my code, which renders a simple menubar:
var SupplierBarComponent = React.createClass({
doSomething: function () {
console.log("aaaaaaaah");
},
render: function() {
const suppliers = this.props.data.map(function(supplier){
return (
<option onClick={this.doSomething} key={supplier.id}>{supplier.name}</option>
);
}, this);
return(
<div>{suppliers}</div>
);
}
How can I make it work? I have read a few similar questions*, but their solutions didn't work for me, or I couldn't make them work.
*: React onClick inside .map then change data in another sibling component "this" is undefined inside map function Reactjs Pass props to parent component in React.js
Upvotes: 1
Views: 5120
Reputation: 942
Your code is working. I have checked it on this Fiddle.I just hardcoded an array instead of the props.
var Hello = React.createClass({
doSomething: function () {
console.log("aaaaaaaah");
},
render: function() {
var data=[{id:1,name:'name 1'},{id:2,name:'name 2'}]
const suppliers = data.map(function(supplier){
return (
<option onClick={this.doSomething} key={supplier.id}>{supplier.name}</option>
);
}, this);
return(
<div>{suppliers}</div>
);
}
})
ReactDOM.render(
<Hello />,
document.getElementById('container')
);
https://jsfiddle.net/evweLre5/
Upvotes: 2