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:


In my opinion the code is 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:


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:

Post a Comment