Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible declaring a variable inside the class and outside the method

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

like image 294
Venkatesh Muthyla Avatar asked Feb 03 '26 20:02

Venkatesh Muthyla


1 Answers

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>
      )
    }
}
like image 108
Estus Flask Avatar answered Feb 05 '26 11:02

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!