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:
why does
{items.map()}
need to be inside curly braces? What principle is being applied here?why does the arrow function inside .map look like
.map(item => (stuff))
vs.map(item => {stuffInsideBraces})
CodePudding user response:
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