React Native ESLint and Prettier config




Install the following packages globally

npm install eslint eslint-plugin-react eslint-plugin-react-native --global

Then install the following packages locally in your react native project

npm install --save-dev eslint eslint-plugin-react eslint-plugin-react-native @babel/eslint-parser prettier eslint-config-prettier eslint-plugin-prettier 

Once the installs are completed initialize eslint,

npm init @eslint/config

Answer the questions as follow,

  • To check syntax, find problems, and enforce code style
  • JavaScript modules (import/export)
  • React
  • No TypeScript
  • Browser and Node
  • Use a popular style guide - Airbnb
  • JavaScript config file
  • Yes install packages

Add react-native to the plugins section

// .eslintrc
{
  "plugins": [
    "react",
    "react-native"
  ]
}

Configure ESLint to support JSX

// .eslintrc.json
{
  "parserOptions": {
    "ecmaFeatures": {
       "jsx": true
    } 
  }
}

Whitelist all browser-like globals by adding react-native/react-native to the config

// .eslintrc.json
{
  "env": {
    "browser": true,
    "react-native/react-native": true,
  }
}

The .eslintrc.js file should now look like this,

module.exports = {
  env: {
    browser: true,
    'react-native/react-native': true,
    es2021: true,
    node: true,
  },
  extends: ['plugin:react/recommended', 'airbnb', 'airbnb/hooks', 'prettier'],
  parser: '@babel/eslint-parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: ['react', 'react-native', 'prettier'],
  rules: {
    'react-native/no-unused-styles': 2,
    'react-native/split-platform-components': 2,
    'react-native/no-inline-styles': 2,
    'react-native/no-color-literals': 2,
    'react-native/sort-styles': [
      'error',
      'asc',
      {
        ignoreClassNames: false,
        ignoreStyleProperties: false,
      },
    ],
    // allow .js files to contain JSX code
    'react/jsx-filename-extension': [1, { extensions: ['.js', '.jsx'] }],
    'import/prefer-default-export': 'off',
  },
};

Create a .prettierrc file and add the following,

{
  "arrowParens": "always",
  "bracketSpacing": true,
  "jsxBracketSameLine": false,
  "jsxSingleQuote": false,
  "quoteProps": "as-needed",
  "singleQuote": true,
  "semi": true,
  "printWidth": 180,
  "useTabs": false,
  "tabWidth": 2,
  "trailingComma": "es5"
}

`'`