ESLint prefer-arrow-callback on array.map

12,700

Solution 1

That ESLint rule occurs because you have an anonymous function as a callback, so it's suggesting that you use an arrow function instead. To use multiple parameters with arrow functions you need to wrap the parameters with parentheses, e.g.:

someArray.map(function(value, index) {
  // do something
});

someArray.map((value, index) => {
  // do something
});

As always, the MDN docs for arrow functions has a very detailed explanation of the variations that can be used with arrow functions.

Alternatively, you could just disable that ESLint rule or change it so that it won't warn about named callbacks. The documentation for that ESLint rule is prefer-arrow-callback.

Solution 2

You could rewrite the map like this:

{colours.map(colour => (
  <div key={`colour-${colour}`} className={`strong color-swatch bg-${colour}`}>
    <p>{colour}</p>
  </div>
)}

Given colour names seem to be unique, you could use them as keys without a problem.

Share:
12,700
azz0r
Author by

azz0r

Updated on July 06, 2022

Comments

  • azz0r
    azz0r almost 2 years
    import React from 'react';
    
    export default class UIColours extends React.Component {
      displayName = 'UIColours'
    
      render() {
        const colours = ['black', 'red', 'white', 'orange', 'green', 'yellow', 'blue', 'darkblue', 'lilac', 'purple', 'darkPurple'];
        return (
          <div className="ui-colours-container row bg-white">
            <div className="col-md-16 col-xs-16 light">
              <div className="color-swatches">
                {colours.map(function(colour, key) {
                  return (
                    <div key={key} className={'strong color-swatch bg-' + colour}>
                      <p>{colour}</p>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
       );
      }
    }
    

    12:26 error Unexpected function expression prefer-arrow-callback

    I've looked at the map documentation and can't find a good example of multiple parameters.