Wednesday, April 13, 2016

Refactoring React components to ES6

Refactoring components to ES6 is going to be inevitable. The trickier parts imho are to refactor state initialisations and state functions.

State Initialisation

React is encouraging to move from getInitialState() to using constructor() method. Example:

Before

  getInitialState: function() {
    return {
      timeElapsed: null
    }
  }

After

  constructor(props) {
    super(props);
    this.state =  {timeElapsed: null};
  }

In my opinion the code is cleaner...so I won't complain!

State Functions

React is removing our comfort zone of auto binding. This is to make is more Javascript idiosyncratic. Again, I won't really complain. Check the before and after example:

Before

..
  startStopButton() {
    return <TouchableHighlight
      underlayColor="gray"
      onPress={this.handleStartPress}
      >
      <Text>
        Start
      </Text>
    </TouchableHighlight>
  }

..

  handleStartPress() {
    var startTime = new Date();

    setInterval(() => {
      this.setState({
        timeElapsed: new Date() - startTime
      });
    }, 30);
  }

After

..
  startStopButton() {
    return <TouchableHighlight
      underlayColor="gray"
      onPress={this.handleStartPress.bind(this)}
      >
      <Text>
        Start
      </Text>
    </TouchableHighlight>
  }

..

Since handleStartPress is going to manipulate the state, it needs to be binded manually to the class object (i.e. our component). Another clean way is to define the bind in the constructor() method:

  constructor(props) {
    super(props);
    this.handleStartPress = this.handleStartPress.bind(this)
    this.state =  {timeElapsed: null};
  }
..
  startStopButton() {
    return <TouchableHighlight
      underlayColor="gray"
      onPress={this.handleStartPress}
      >
      <Text>
        Start
      </Text>
    </TouchableHighlight>
  }

..

Post a Comment