3
class Counter extends React.Component {
    var a = 'bla bla';
    render(){ 
    return (
     <h1>{a}</h1>
    )

}
}

1) I had described a variable inside the class

2) I am getting error i know that i have to declare inside the render method but i want know why we shouldn't declare outside render and inside class

class Counter extends React.Component {
        var a = 'bla bla';
        render(){ 
        return (
         <h1>{this.a}</h1>
        )

    }
    }

I have used this also still i am getting error

class Counter extends React.Component {

    render(){ 
        var a = 'bla bla';
    return (
     <h1>{a}</h1>
    )

}
}

The following code solves my problem but i want to know why i got error on my previous step

  • A good explanation on the status of class variables. https://stackoverflow.com/questions/22528967/es6-class-variable-alternatives – kvnam Jan 12 '19 at 10:04

1 Answers1

1

Variables are defined in some scope. There is no scope for entire class. Once ES6 classes are used, it's beneficial to have a good understanding of how they work.

class Counter {
  constructor() {...}
  render() {...}
}

is syntactic sugar for

function Counter() {
  // constructor
}
Counter.prototype.render = function () {...}

There is no place where a variable could be defined on every class instantiation and be available in both constructor and render method.

This is possibly use case for class fields, which are stage 3 proposal:

class Counter extends React.Component {
    a = 'bla bla';

    render(){ 
      return (
       <h1>{this.a}</h1>
      )
    }
}

This isn't suitable if a is a constant. Then it doesn't benefit from being reassigned every time and could be a constant:

const a = 'bla bla';

class Counter extends React.Component {
    render(){ 
      return (
       <h1>{a}</h1>
      )
    }
}
Estus Flask
  • 206,104
  • 70
  • 425
  • 565