Search code examples
javascriptreactjsjsxeslintprettier

Code Formatting: Add space around binary operators in JSX code


I noticed that any JavaScript inside my file was getting correctly formatted (spaces being inserted correctly between operators by Prettier) but for JSX code the spaces do not get inserted correctly.

Example-
enter image description here

This is my .eslintrc.json file-

{
    "env": {
        "browser": true,
        "es6": true
    },
    "extends": ["react-app", "prettier"],
    "parserOptions": {
        "ecmaVersion": 12
    },
    "plugins": ["react", "prettier"],
    "rules": {
        "prettier/prettier": [
            "error",
            {
                "singleQuote": true,
                "trailingComma": "es5",
                "jsxBracketSameLine": true,
                "useTabs": true,
                "endOfLine": "auto",
                "jsxSingleQuote": true
            }
        ],
        "arrow-body-style": "off",
        "prefer-arrow-callback": "off",
        "quotes": ["error", "single"],
        "space-infix-ops": ["warn", { "int32Hint": false }],
        "space-unary-ops": [
            "warn",
            {
                "words": true,
                "nonwords": false,
                "overrides": {
                    "++": true
                }
            }
        ]
    }
}

Is there any property I can add for Prettier or Eslint that allows me to add spaces between operators in JSX. Or an extension or any other way to solve formatting inconsistencies like these ?


Solution

  • If you need to use Prettier, this appears to be impossible. However, if you're fine with giving Prettier up, eslint-plugin-react provides an ESLint rule which allows you to require spaces around the equals sign: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-equals-spacing.md.

    "react/jsx-equals-spacing": ["error", "always"]