ReactJS Class Attributes

React classes have a few quirks that aren’t obvious to developers that are new to React (and maybe the JavaScript universe).

Classes and Attributes

ReactJS classes are actually ES6 classes with Babel syntactic sugar thrown in. For example, coming from other languages, you might expect class attributes to use the form

or

However, that doesn’t work. In ES6 classes, you cannot add attributes directly to the class. They are actually added after the class is defined–very ugly and painful to look at.

Babel compiles/transpiles React classes, though. So, you get the ability to add class attributes using either of the following syntaxes.

or

The first you access using this, as in this.somevar and the second you access using a the class name,  as in MyClass.somevar.

Don’t Forget ‘this’

Since we mentioned this, don’t forget about binding this to your methods before using it. (Bindings in JavaScript are always such a joy.)

If you create your methods in your ReactJS classes using the arrow method, then you have the class’s this, already.

However, if you create your methods using the following approach, then this may not be the this you are looking for. (It won’t be the class’s this when you call it.)

In previous case, bind the class’s this to the method explicitly in the constructor of the class with the following code.