Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

How To Easily Add ESLint To A React Project

Adding ESLint rules to a React project will improve the quality of your codebase. Some of the benefits are consistency across all files which can reduce bugs overall.

ESLint is a popular open-source JavaScript which automatically detects incorrect coding patterns found in your codebase.

Let’s learn how to add ESLint to a React app with the steps below:

Installing ESLint in React App

First, we need to install ESLint in our React project as a devDependencies because we don’t need them in production.

To Install, we will use the command below.

Bash
npm i -D eslint

Initialize ESLint

Next, we will have to initialize ESLint configuration, by adding a configuration file .eslintrc.json in our project’s root folder.

Here is a sample example configuration.

JSON
{
  "extends": [
    "eslint:recommended",
    "plugin:import/errors",
    "plugin:react/recommended",
    "plugin:jsx-a11y/recommended"
  ],
  "plugins": ["react", "import", "jsx-a11y"],
  "rules": {
    // Here we can add our custom rules.
  },
  "parserOptions": {
    "ecmaVersion": 2021,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "env": {
    "es6": true,
    "browser": true,
    "node": true
  },
  "settings": {
    "react": {
      "version": "detect"
    }
  }
}

Inside our .eslintrc.json add extends and plugin property.

JSON
{
  "extends": [
    "eslint:recommended",
    "plugin:import/errors",
    "plugin:react/recommended",
    "plugin:jsx-a11y/recommended"
  ],
  "plugins": ["react", "import", "jsx-a11y"]
}

As we have added various plugins we need to first install them as devDependencies by running the given command below.

Bash
npm install -D eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react

Adding Rules

Rules are used for configuration purposes. We can set the error level of rules in three different ways.

  • off or 0: This will turn off the rule.
  • warn or 1: This will turn the rule on as a warning.
  • error or 2: This will turn the rule on as an error.

Let’s add some rules to our configuration file, we can add any other rules as per our choice from the list of all rules mentioned above.

JSON
"rules": {
  "react/prop-types": 0,
  "indent": ["error", 2],
  "linebreak-style": 1,
  "quotes": ["error", "double"]
}

What Are ESLint Plugins and Presets?

ESLint plugins and presets are just like libraries and packages we install for React. They extend the functionality and features of ESLint that the tool doesn’t have out of the box for JavaScript.

There are millions of libraries and it would be impossible for the ESLint team to add support for all so the libraries themselves will create plugins and presets to support their library. More specifically:

Presets are a collection of rules bundled together that can be easily extended into your ESLint configuration. They provide a base set of rules that you can build upon or modify according to your project’s needs.

Plugins, on the other hand, add specific rules or extend ESLint’s capabilities. For example, they can add rules related to React components, accessibility, or import/export statements.

Why Do We Need Plugins and Presets?

To ensure the packages that you use are properly handled by ESLint. The main 4 categories are library specific rules, accessibility, module import/export validation and standardizing coding practices.

Use the rules and customizing it with your projects and repo will ensure consistency no matter who writes the code. The hope is with cleaner and standardized code it will create good coding practices. Thus resulting in easier development, better developer experience, fewer bugs and a more maintainable codebase.

Adding Scripts for Linting

Last but not least, let’s add some commands in our package.json “scripts” property to run ESLint.

JSON
"scripts": {
  "lint": "eslint \"src/**/*.{js,jsx}\"",
  "lint:fix": "eslint \"src/**/*.{js,jsx}\" --fix"
}

Congrats, now if you try to run either of these commands it should do the trick!

After this you can continue to customize the linting rules to your liking to ensure code consistency and quality.

Tip: Learn some useful mac terminal commands.

Using ESLint in VSCode

If you’re like the millions using VSCode then you may benefit from adding ESLint in VSCode itself rather than per project. The steps are very simple:

  • Download VSCode if you don’t have it already
  • Go to Extenstions in VSCode and install ESLint
  • To customize it further open up .vscode/settings.json

In .vscode/settings.json you’ll see a JSON file and can add/modify rules, for example:

JSON
{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact"
  ]
}

The rules above tells VSCode to apply ESLint fixes every time you save a file.

How To Fix Common ESLint Errors

As you start using ESLint you’ll come across some common errors and before you start get familiar with the 5 common ones below.

Parsing Error: Unexpected Token

Issue: This error often occurs when ESLint encounters syntax that it doesn’t understand, such as newer JavaScript features or JSX.

Solution: Ensure that your parserOptions in .eslintrc.json are set correctly to support the syntax you’re using. For example, if you’re using ES6+ or JSX, your configuration should include:

JSON
"parserOptions": {
  "ecmaVersion": 2021,
  "sourceType": "module",
  "ecmaFeatures": {
    "jsx": true
  }
}

X is defined but never used (no-unused-vars)

Issue: This error indicates that you have declared a variable or function but have not used it anywhere in your code. ESLint flags these as potential issues because unused code can lead to confusion and clutter.

Solution: Check your code to see if the variable or function is necessary. If not, you can remove it. If it is necessary but not yet used, consider using a comment to disable the rule for that specific line:

JavaScript
// eslint-disable-next-line no-unused-vars
const myVar = "Hello, world!";

X should be placed at Y position (react/sort-comp)

Issue: The react/sort-comp rule enforces consistent method order in React components, which can lead to errors if your methods are not in the expected order.

Solution: Reorder your component’s methods according to the rule’s expected order. Usually this means placing lifecycle methods first, then event handlers, and then render methods. You can customize this order in your ESLint configuration if needed:

JSON
"rules": {
  "react/sort-comp": [
    2,
    {
      "order": [
        "static-methods",
        "lifecycle",
        "everything-else",
        "render"
      ]
    }
  ]
}

X must be in scope when using JSX (react/react-in-jsx-scope)

Issue: This error occurs in projects that use React versions before 17, where React must be in scope when using JSX.

Solution: Confirm that import React from “react”; is included at the top of your JSX rules. In React 17 and later, this is no longer necessary due to the new JSX transform, so upgrading React can also resolve this issue.

Inconsistent linebreak style (linebreak-style)

Issue: This error arises when your project has mixed line endings (e.g., LF for Unix/MacOS and CRLF for Windows).

Solution: Standardize your linebreaks across the project. You can set the linebreak-style rule in ESLint to enforce consistent line endings:

JSON
"rules": {
  "linebreak-style": ["error", "unix"] // or "windows"
}

Additionally, configure your editor to use the same line ending style for all files.

Final Words

By understanding and addressing these common ESLint errors, you can maintain a clean, efficient codebase and avoid potential pitfalls in your React development process.

Tip: I’ve compared the best CMS for React and Nextjs projects. Make sure to check it out.

Jenesh Napit
Jenesh Napit

Currently a Software Engineering Manager, managing 2 teams. Previously a Senior Software Engineer. Besides writing articles, I also provide career coaching for aspiring engineers looking to get their first role and help get promotions in their current roles.