Maximus S Maximus S - 29 days ago 17
React JSX Question

React: "this" is undefined inside a component function

class PlayerControls extends React.Component {
constructor(props) {
super(props)

this.state = {
loopActive: false,
shuffleActive: false,
}
}

render() {
var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"

return (
<div className="player-controls">
<FontAwesome
className="player-control-icon"
name='refresh'
onClick={this.onToggleLoop}
spin={this.state.loopActive}
/>
<FontAwesome
className={shuffleClassName}
name='random'
onClick={this.onToggleShuffle}
/>
</div>
);
}

onToggleLoop(event) {
// "this is undefined??" <--- here
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}


I want to update
loopActive
state on toggle, but
this
object is undefined in the handler. According to the tutorial doc, I
this
should refer to the component. Am I missing something?

Answer

ES6 React.Component doesn't auto bind methods to itself. You need to bind them yourself in constructor. Like this:

constructor (props){
  super(props)

  this.state = {
      loopActive: false,
      shuffleActive: false,
    }

  this.onToggleLoop = this.onToggLoop.bind(this)

}