1

I am new to react. While studying it I came across map function. The guy was making a quiz app and used map to iterate over an answers array as:

{this.state.allQuestions[this.state.currentQuestion].answerOptions.map((answerOption) => (
                      <button onClick={() => this.handleAnswerOptionClick(answerOption.isCorrect)}>{answerOption.answerText}</button>
                    ))}
//allQuestions is an array which contains question as well as an array of its options (answerOptions).

While I am using the same method to iterate over a normal array I do not get the desired result, unless I use return statement. Here is my code:

function Component() {
      const arr = [1,2,3,4,5];
      return (
        <div>
          <h1>Component</h1>
          {arr.map((item) => {
            <button>{item}</button> //does not return anything
            //return <button>{item}</button>  Gives the output
          })}
        </div>
      );
    }

Why is that return is required here but not in the first case?

1 Answers1

1

The type of function you (and the quiz) uses is called an arrow function. Arrow function have some benefits, one of which being that you can sometimes omit the return keyword.

According to the MDN (source):

One param. With simple expression return is not needed:

param => expression

and

Multiline statements require body brackets and return:

param => {
  let a = 1;
  return a + param;
}

To answer your question - the reason it does not work in your code is because you are trying to do the 2nd method shown above (using curly braces, which require return), whereas the quiz uses the first syntax (where return is not needed).

Chris
  • 57,622
  • 19
  • 111
  • 137