notalentgeek
notalentgeek

Reputation: 5829

How can I have class-wide constant in my React Component class?

Usually I do this:

var tagSymbols = Object.freeze([
  '!',
  '+',
  '@'
]);

But then I know there is const from Babel (?).

const tagSymbols = Object.freeze([
  '!',
  '+',
  '@'
]);

Both return the same error:

Syntax error: Unexpected token (4:6)

  2 | 
  3 | class GeneralToDoListInput extends Component {
> 4 |   var tagSymbols = Object.freeze([
    |       ^
  5 |     '!',
  6 |     '+',
  7 |     '@'

Syntax error: Unexpected token (5:8)

  3 | class GeneralToDoListInput extends Component {
  4 | 
> 5 |   const tagSymbols = Object.freeze([
    |         ^
  6 |     '!',
  7 |     '+',
  8 |     '@'

Upvotes: 10

Views: 24384

Answers (1)

Felix Kling
Felix Kling

Reputation: 816970

You cannot put variable declarations inside a class body. That's just not allowed by the language. In ES6, the structure of a class declaration is basically

class Foo() {
  method1() {}
  method2() {}
  ...
}

The simplest solution would be to put the variable declaration outside of the class:

const tagSymbols = ...:
class GeneralToDoListInput extends Component {
  ...
}

Any code inside the class/module can access tagSymbols.

If it really has to be a class property you can either define a static getter:

class GeneralToDoListInput extends Component {
  static get tagSymbols() {
    return Object.freeze(...);
  }
}

Or assign it to the class after the declaration:

class GeneralToDoListInput extends Component {
  ...
}
GeneralToDoListInput.tagSymbols = ...;

Upvotes: 23

Related Questions