React class method 0.13 undefined

So, I started working with React and ES6 and 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> ); } } 
+7
javascript ecmascript-6 reactjs
source share
2 answers
 {menuItems.map(function(item) { return <li className={active ? 'active' : ''} onClick={this.handleClick.bind(this)} key={item.id}>{item.text}</li>; })} 

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

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

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

Or use the arrow function :

 {menuItems.map( item => <li className={active ? 'active' : ''} onClick={this.handleClick.bind(this)} key={item.id}>{item.text}</li> )} 
+12
source share

react.js:18794 Warning: bind(): You are binding a component component to a component. React does this automatically for you in a high-performance way, so you can safely remove this call. See BlueBall

so simple:

 { menuItems.map( item => <li className={active ? 'active' : ''} onClick={this.handleClick} key={item.id}>{item.text}</li> )} 
0
source share

All Articles