Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 |     '@'
like image 917
notalentgeek Avatar asked Nov 03 '17 17:11

notalentgeek


People also ask

How do I add a constant to my React project?

You can simply create an object for your constants: const myConstClass = { ACTION_INVALID: "This action is invalid!" } And then use it. If you are bundling, you can export this object and then import for each component file.

How do you declare a global variable in React class?

Create a file : import React from "react"; const AppContext = {}; export default AppContext; then in App. js, update the value import AppContext from './AppContext'; AppContext. username = uname. value; Now if you want the username to be used in another screen: import AppContext from './AppContext'; AppContext.

Where do you keep constants in React?

All you have to do is take each section of your constants that are currently within index. js and put them within own their brand new file in /src/constants and link them to our constants/index.


1 Answers

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 = ...;
like image 136
Felix Kling Avatar answered Oct 24 '22 13:10

Felix Kling