1

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

Community
  • 1
  • 1
handris
  • 1,999
  • 8
  • 27
  • 41
  • If you console.log this in the map function is it return the component object? – finalfreq Nov 22 '16 at 17:42
  • Yes, it does. If I call it by console.log(this.doSomething) - so without ()s, it prints the function itself: 3models.jsx:9() { console.log("aaaaaaaah"); } If I call it with parentheses, it prints 'undefined' first on, but the function still gets called, and it prints out 'aaaah'. – handris Nov 22 '16 at 17:54
  • Do you need to do `this.doSomething.bind(this)` ?? depending on your usage of this inside doSomething? Also, you should get a synthetic event object that will include more information... – Tracker1 Nov 22 '16 at 19:07

1 Answers1

2

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/

Vaibhav Singh
  • 932
  • 7
  • 20