Search code examples
javascriptarraysreactjsecmascript-6arrow-functions

Is There a Syntax to Remove the First Parameter from a map() Arrow Function?


Is there a way to keep the first parameter n in the map() as a void? I am creating CSS shapes, so I only need the second one.

Thanks!

const Star = () => {
  return (
   <div id='Star'>
     {[...Array(3)].map((n, i) => <span style={{transform: `rotate(${i * 50}deg)`}}/>)}
    </div>
  )
}   

ReactDOM.render(
  <Star/>,
  document.getElementById("root")
);
#Star {
    position: fixed;
    left: 50%;
    top: 50%;
}
#Star span {
    background: green;
    width: 20px;
    height: 20px;
    display: block;
    position: absolute;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


Solution

  • There's no really clean way to do it afaik. There are few options I can think of:

    1. Declaring unused arg as _. In this case the _ variable will still be initialised, so the benefits are only visual.
    [...Array(3)].map((_, i) => <span style={{transform: `rotate(${i * 50}deg)`}}/>)
    
    1. Using rest params
    [...Array(3)].map((...params) => <span style={{transform: `rotate(${params[1] * 50}deg)`}}/>)
    

    Could be also written inline, which might be a bit confusing.

    [...Array(3)].map((...[,i]) => <span style={{transform: `rotate(${i * 50}deg)`}}/>)