Define variable and return component inside .map()

Question!

I'd like to define a variable inside a .map() iteration, as well as returning a component.

But having this variable inside the map doesn't work (gives me error). Is this possible at all, and if so how do I do this?

Below is a simplified example of what I'm trying to do:

render() {
  return(
    <div>
      {array.map( (element, index) => (
        let disturbingVariable = 100 + index
        <MyComponent disturbingVariable={disturbingVariable} />
      ))}
    </div>
  )
}


Answers

This is because you are trying to implicitly return value from a function instead of explicitly by using a return statement. If you want to return a value as well as do other operations, you will have to do something like this:-

Notice () converts to {} and use of return statement to explicitly return the component.

render() {
  return(
    <div>
      {array.map( (element, index) => {
        let disturbingVariable = 100 + index
        return <MyComponent disturbingVariable={disturbingVariable} />
      })}
    </div>
  )
}


When an arrow function has more than one statement you can no longer use the implicit return syntax.

Add block braces and a return statement:

array.map((element, index) => {
  let disturbingVariable = 100 + index
  return <MyComponent disturbingVariable={disturbingVariable} />
})

Alternatively, forgo the variable declaration and perform the addition in-place, maintaining the implicit return:

array.map((element, index) =>
  <MyComponent disturbingVariable={100 + index} />)
By : sdgluck


Alternatively, you could omit return and block braces, but the function body should be one liner with implicit return:

render() {
  return(
    <div>
      {array.map((element, index) => <MyComponent disturbingVariable={100 + index}/>)}
    </div>
  )
}

More about implicit return here

By : leo


This video can help you solving your question :)
By: admin