Skip to content Skip to sidebar Skip to footer

Trying To Convert React.createclass To Extends React.component

I'm trying to convert a sample written with React.CreateClass to extends React.Component but the eventhandler doesn't get the state and fails on me. Can someone shed some light on

Solution 1:

With class methods, the this is not automatically bound to class (except for constructor and React lifecyle methods).

Solution 1

Bind the functions to this inside the constructor:

constructor() {
    super();
    this.state = {
        username: '',
        password: ''
    };
    this.handleChange = this.handleChange.bind(this);
    this.changeFunkyShizzle= this.changeFunkyShizzle.bind(this);
}
handleChange(key) {
    return function (e) {
        var state = {};
        state[key] = e.target.value;
        this.setState(state);
    }.bind(this);
}
changeFunkyShizzle() {
    this.setState({
        username: 'Tom',
        password: 'Secret'
    });
}

Solution 2

Use arrow functions. As this is a ES6 feature, you might need to configure Babel with the correct plugin.

handleChange = (key) =>(e) => {
  var state = {};
  state[key] = e.target.value;
  this.setState(state);
}

changeFunkyShizzle = () => {
   this.setState({
       username: 'Tom',
       password: 'Secret'
   });
}

Solution 3

Use an autobinding third party library to do this for you:

Post a Comment for "Trying To Convert React.createclass To Extends React.component"