Search code examples
reactjseslintprettier

Rendering a list in React and get Eslint error "no unused expressions"


I'm relearning eslint and am doing a test config for in create react app and also including prettier for formatting. The error states Failed to compile: 'Expected an assignment or function call and instead saw an expression no-unused-expressions'. I went to the eslint docs https://eslint.org/docs/rules/no-unused-expressions and added the 'allows' to the rules section. How do I fix this and is this maybe a prettier formatting conflict with eslint?

The error points to the line where the list item starts.

<div>
    <ul>
      {this.state.list.map((item, index) => {
        <li key={index}>
          {item}
          <button
            type="button"
            onClick={() => {
              this.onRemoveItem(index);
            }}>
            Remove
          </button>
        </li>;
      })}
    </ul>
  </div>

Here is my .eslintrc.json

{
  "extends": ["prettier", "prettier/react"],
  "plugins": ["react", "jsx-a11y", "import", "prettier"],
  "rules": {
    "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
    "prettier/prettier": "error",
    "arrow-body-style": ["warn", "always"],
    "allowShortCircuit": true,
    "allowTernary": true
  },
  "parser": "babel-eslint",
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true,
      "modules": true
    }
  },

  "env": {
    "browser": true,
    "node": true,
    "es6": true,
    "node": true
  }
}

Solution

  • Return value is unused and thus error is thrown:

    <div>
        <ul>
          {this.state.list.map((item, index) => {
            return (
             <li key={index}>
              {item}
              <button
                type="button"
                onClick={() => {
                  this.onRemoveItem(index);
                }}>
                Remove
              </button>
            </li>
           );
          })}
        </ul>
      </div>
    

    You may also use parentheses to return the object:

    <div>
        <ul>
          {this.state.list.map((item, index) => (
             <li key={index}>
              ...
            </li>
          ))}
        </ul>
      </div>
    

    Or, even if you start <li> in the same line, you may avoid:

    {this.state.list.map((item, index) => <li key={index}>
       ...
      </li>
    )}