-1

I'm taking an online course to learn react. A student posted a solution to a problem that I think is really elegant and I'd like to understand better. The code iterates through an array of items to create a list in the UI.

function ItemsMaker({items}) {

  return (

    <div className="itemblocks">

      {items.map(item => (

        <ExpenseItem

          title={item.title}

          amount={item.amount}

          date={item.date} />

      ))}

    </div>

  )

}

I think it's really elegant the way the props object is destructured as a parameter to the function. But I'd like to understand better:

  1. why does {items.map()} need to be inside curly braces? What principle is being applied here?

  2. why does the arrow function inside .map look like .map(item => (stuff)) vs .map(item => {stuffInsideBraces})

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Monjoie11
  • 33
  • 5
  • 1. The principle of that being JSX. 2. See dupe. (Note neither is related to the props parameter destructuring.) – jonrsharpe Mar 03 '22 at 16:15
  • Does this answer your question? [Arrow function without curly braces](https://stackoverflow.com/questions/39629962/arrow-function-without-curly-braces) – jonrsharpe Mar 03 '22 at 16:15
  • Yes I think so. {items.map()} is returning an object and .map(item => (stuff)) is performing a function on each value in the items array without returning anything? – Monjoie11 Mar 03 '22 at 16:27

1 Answers1

0

Answer to question 1 - While writing JSX if you want to access a variable that was initialized in that function you have to use the curly braces syntax to use that variable and access its properties/values. So lets say you have a function like below -

showName = ({name}) => {
   let text = "MY NAME IS"
   return (<div>{text + name}</div>);
}

showName("BLABLA")

so above function should return an output like below -

MY NAME IS BLABLA

Answer to question 2 -

Basically when you have an array of data like the above example given if we want to access that data we write it inside curly braces and if you want to return a plain jsx for each array object we can do that by just returning a plain jsx that we want to return.

example:

showName = ({listOfName}) => {
  let text = "MY NAME IS"
  return (
   {listOfName.map(name=> (<div> {text + name} </div>))}
  )
}
showName(["Xname", "Yname"])

So in the above example you will see that the text is printed twice

MY NAME IS Xname
MY NAME IS Yname
Sofiya rao
  • 86
  • 1
  • 11