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

After
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

After
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