HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactCritical

React: "this" is undefined inside a component function

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
undefinedfunctionreactinsidethiscomponent

Problem

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

  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?

Solution

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.onToggleLoop.bind(this);

}

Code Snippets

constructor (props){
  super(props);
  
  this.state = {
      loopActive: false,
      shuffleActive: false,
    };
  
  this.onToggleLoop = this.onToggleLoop.bind(this);

}

Context

Stack Overflow Q#33973648, score: 284

Revisions (0)

No revisions yet.