Using Decorators in Your React Project

Using Decorators

Currently only supports Babel/TypeScript preprocessors

Babel:

npm install  babel-plugin-transform-decorators-legacy --save-dev

Add it to your .babelrc configuration file. If you don’t have a .babelrc file, create one.

{
  "presets": [
    "es2015",
    "stage-1"
  ],
  "plugins": ["transform-decorators-legacy"]
}

The plugin order is very important: transform-decorators-legacy should be the first plugin.

When using React Native, the following preset can replace transform-decorators-legacy:

{
  "presets": ["stage-2", "react-native-stage-0/decorator-support"]
}

Using Decorators in create-react-app

npm run eject

Install the related plugins:

//for react
npm install babel-preset-stage-2 --save-dev
npm install babel-preset-react-native-stage-0 --save-dev

Create .babelrc in the root directory:

{
  "presets": ["react-native-stage-0/decorator-support"]
}

TypeScript

If your project is already using TypeScript, simply set experimentalDecorators to true in your tsconfig.json file.

This way, we can use the ES7 decorator feature.

Remove Decorator Syntax Warnings in VSCode

Create a tsconfig.json in the project root:

{
    "compilerOptions": {
        "experimentalDecorators": true,
        "allowJs": true
    }
}

Restart your VSCode and the syntax warnings will be gone.

Article Link:

/en/archive/react-decorator/

# Related Articles