Using 'this' in react components for variables - common style/convention?

Using 'this' in react components for variables - common style/convention?
0.0 0


Hi All,

I was reading through the code of an interesting project I saw on Github (react-dropzone). I noticed that in a lot of cases when they were declaring a variable within a function they would do something like this:

  this.dragTagets = [];
  //other stuff below...

What struck me is that I have never done this in any of my React apps so I was wondering why the collaborators of the project are declaring variables in this way?

From what I understand when you’re writing a react class you are writing a blueprint of the eventual DOM instance. React, behind the scenes will instantiate an instance of the class, render it and attach it to the dom.

A crude representation:

class Foo{
    this.state = {
      greeting: 'Hello'
    this.stuff = 'apple';
    return '<p>' + this.state.greeting + '</p>' //"JSX" hehe

let foo = new Foo();

foo.doStuff(); //sets this.stuff, could do this in constructor too
foo.logStuff(); //apple
foo.render(); //<p>Hello</p>

So I suppose when you declare a variable like such (this.variable = 'baz';) you are making it accessible to ALL of the functions within the class - ie. you almost make it like a global within that class/component?

Would that be the main reason for declaring variables in that manner? As I said, I’ve never done this before and would typically just use let or const within the functions in the component. If I need the variable to accessible throughout the entire component I would consider declaring it in the components state

Any thoughts?

Thanks All.


Hi Swoodend,

The ‘this’ key word is especially helpful for more complex applications that have multiple “child” components to a specific parent component, or “Super Class”.

So for example in your render function what if instead of returning:

'<p>' + this.state.greeting + '</p>' //"JSX" hehe

Instead you wanted to embed another component that you defined like…

<div><MyChildComponent /></div>

And lets say you want this child component to use the “doStuff” function declared in your component “Foo”. Well you could pass the method down like this…

<div><MyChildComponent doStuff={this.doStuff.bind(this)}/></div>

…Then you can define MyChildComponent this way…

class MyChildComponent extends React.Component {

I’d research a little bit why you would want to use the method .bind, what “props” are and what “super” is, but in essence without the ‘this’ key word, gives the MyChildComponent reference to which method MyChildComponent is referring to (the method on the component “Foo”.