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:
componentDidMount(){
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{
constructor(){
this.state = {
greeting: 'Hello'
}
}
doStuff(){
this.stuff = 'apple';
}
logStuff(){
console.log(this.stuff);
}
render(){
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.