Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React 0.13 class method undefined

So i've started with React and ES6 and got stuck with very basics. Really appreciate some help.

handleClick() throws an error:

Uncaught TypeError: Cannot read property 'handleClick' of undefined

code follows

export default class MenuItems extends React.Component {

  constructor(props) {
    super(props)
    this.state = {active: false}
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    this.setState({ active: !this.state.active });
  }

  render() {
    let active = this.state.active
    let menuItems = [{text: 'Logo'}, {text:  'promo'}, {text:     'benefits'}, { text: 'form'}]
    return (
      <ul>
        {menuItems.map(function(item) {
          return <li className={active ? 'active' : ''} onClick={this.handleClick.bind(this)} key={item.id}>{item.text}</li>;
        })}
      </ul>
    );
  }
}
like image 833
walkthroughthecode Avatar asked Apr 09 '15 21:04

walkthroughthecode


1 Answers

{menuItems.map(function(item) {
  return <li className={active ? 'active' : ''} onClick={this.handleClick.bind(this)} key={item.id}>{item.text}</li>;
})}

Because your code is in strict mode (modules are always in strict mode), this is undefined inside the function you pass to .map.

You either have to explicitly set the context by passing a second argument to .map:

{menuItems.map(function(item) {
  // ...
}, this)}

Or use an arrow function:

{menuItems.map(
     item => <li className={active ? 'active' : ''} onClick={this.handleClick.bind(this)} key={item.id}>{item.text}</li>
)}
like image 143
Felix Kling Avatar answered Oct 16 '22 19:10

Felix Kling