Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
Why is "..." required before a function call that is being passed as an expression inside map function in React with typescript

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda