Why this cannot be used without constructor

I am learning React and I am confused over why we need this inside of the constructor, when I omit the constructor, it gives me a red line, like in the attached image. why does it give a red line under this without a constructor?
Screenshot 2021-02-21 at 2.01.14 PM

Why would you do that?

I guess if you remove the this keyword and turn it to a class field instead it will be a JavaScript code nonetheless

Hello there,

Remember, classes are not a React thing - they are plain JavaScript. So, anything at the root scope of the class is either:

  • A method
  • A field property

Neither of which is declared using the this keyword - just the syntax used.

I recommend you read more about the class syntax: Classes - JavaScript | MDN (mozilla.org)

Hope this helps

2 Likes

my bad when I make it sound classes are react things, what I don’t understand is why this is having a red line if there is no constructor? MDN is very confusing for me

The same reason this gets a red line - incorrect syntax:
image

The parser does not know what you want to do with the code. If you are using a decent editor, it should explain the issue:

Hope this clarifies

1 Like

According to w3school site, the this keyword is used to refer to the object it belongs to. So the value of it will depend in the context of which you use it.

So if you’re using the keyword this it has to be under the context in which is made for. Like our friend up said, if you want to use that keyword you must give the expected token(the piece of code what it expects in under to work properly).

I don’t know react but I suspect this post might help you understand both the JS this keyword and React class components in regards to the this keyword:

Hope this helps, Happy Codding!
:>

And just to be clear, when building a class for React, you can just assign state to the class as a property. You’re taught to do this:

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { num: 42 };
  }

  render() {
  // ...

But the class comes with a default constructor so if you aren’t doing anything fancy, you don’t need to state one. You can assign state directly:

class MyComponent extends Component {
  state = { num: 42 };

  render() {
  // ...

Why do you need to say “this” in the first case? Because you want to make it clear that you want “state” to be a property of the class and not just an undeclared global variable called “state”. In the second case, “this” is not necessary because you are adding it directly as a class property and it can’t be anything but a class property. That’s for the same reason that you don’t have to say “this.render” when you declare that - from context it is clear that it is a class method.

1 Like