javascript - React 0.13 class method undefined -


so i've started react , es6 , got stuck basics. appreciate help.

handleclick() throws 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>     );   } } 

{menuitems.map(function(item) {   return <li classname={active ? 'active' : ''} onclick={this.handleclick.bind(this)} key={item.id}>{item.text}</li>; })} 

because code in strict mode (modules in strict mode), this undefined inside function pass .map.

you either have explicitly set context passing second argument .map:

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

or use arrow function:

{menuitems.map(      item => <li classname={active ? 'active' : ''} onclick={this.handleclick.bind(this)} key={item.id}>{item.text}</li> )} 

Popular posts from this blog