So, I am trying to render a list of items, and want to style the background depending on a certain prop's value.
I opted to use the .map function.
The code look like this:
itemCards.map((item) =>
<div key= {item.id} className={'list_card'} {getCardColor(item)}>
The issue here is that Typescript is insisting I put the the spread operator (...) before the function call of getColorCard.
So it should look like this:
itemCards.map((item) =>
<div key= {item.id} className={'list_card'} {...getCardColor(item)}>
and the function getCardColor look like this:
function getCardColor(item: ItemCard): React.CSSProperties {
if(item.priority === null){
return ({background:"red"})
}
return ({background:"black"})
}
It works.
My question would be why do I need a spread operator before the function call in my case?
Sorry if this was asked before, but I don't how to search for it on Google.
Edit: I put in what getCardColor returns
JSX syntax essentially converts to calling a function and passing it an argument which is an object made up of the props and their values.
<Func foo="bar" />
is roughly the same as:
const props = { foo: "bar" };
Func(props);
If you have an object with some props and values already, then you can use the spread operator to combine two objects.
<Func foo="bar" a={1} />
const moreProps = { a: 1 };
const props = { foo: "bar", ...moreProps };
Func(props);
You can do the spreading inside the JSX:
<Func foo="bar" {...moreProps} />
But you can't just slap in a value by itself like that.
const props = { "a value" };
That's an error in JS.
So you have to spread the return value of the function.
However, your function returns undefined so putting it in the middle of JSX like that is nonsensical in the first place.