Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ESLint prefer-arrow-callback on array.map

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.

like image 861
azz0r Avatar asked Apr 16 '16 09:04

azz0r


2 Answers

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.

like image 143
Scott Avatar answered Nov 05 '22 19:11

Scott


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.

like image 25
Juho Vepsäläinen Avatar answered Nov 05 '22 20:11

Juho Vepsäläinen