Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This scope in a simple React component

Have an issue with, i think, scope when it comes to this.onItemClick in my Filter component.

Getting an error "onItemClick is not defined".

Here's the code for the Filter component.

var Filter = React.createClass({
getDefaultProps() {
    return {
      filterList: [],
      name: ''
    };
},
onItemClick(event) {
    event.currentTarget.style.backgroundColor = '#f00';
},
render() {
    return (
        <div className="filterCloud quarter-section">
            <h3>{this.props.name}</h3>
            <ul>
              {this.props.filterList.map(function(listValue) {
                  return <li onClick={this.onItemClick}>{listValue}</li>;
              })}
              </ul>
        </div>
    )
}});
like image 515
Krešimir Čoko Avatar asked May 12 '26 19:05

Krešimir Čoko


1 Answers

You should set this for .map callback, because now this refers to global scope(in browser it is window, or undefined if you use strict mode)

this.props.filterList.map(function(listValue) {
   return <li onClick={this.onItemClick}>{listValue}</li>;
}, this);
   ^^^^^
like image 183
Oleksandr T. Avatar answered May 14 '26 09:05

Oleksandr T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!