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
1 |
let somevar = 42; |
or
1 |
const somevar = 42; |
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.
1 |
somevar = 42; |
or
1 |
static somevar = 42; |
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.
1 2 3 |
myMethod = () => { return this.something; } |
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.)
1 2 3 |
myMethod() { return this.anything; } |
In previous case, bind the class’s this to the method explicitly in the constructor of the class with the following code.
1 |
this.myMethod.bind(this); |