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

331
Visualizações
Sending in a prop object where some are dependant on a boolean value without addition object creation

I have the following component taking in the prop data.

<Button
    data={booleanValue && {
        d: 4,
        // another 8 key/values
    }}
/>

So data value only gets passed in if booleanValue is true.

But I also have another 3 more value which I wish to add inside this data which are meant to always show. So show irregardless of whether booleanValue is true or false.

Is there a way I could write this elegantly within the component above itself?

I could create the object separately like following which would work. But trying to see if I could achieve it without additional object creation.

One possible solution but don't want to create an object like this.

let obj = {
    a: 1,
    b: 2,
    c: 3,
};

if (booleanValue) {
    obj['d'] = 4;
    // more values being added same way.
}

<Button
    data={obj}
/>

Attempted the following but it doesn't capture the keys a,b,c.

<Button
    data={{
        a: 1,
        b: 2,
        c: 3,
    } && booleanValue && {
        d: 4,
        // more values being added same way.
    }}
/>

Possible solutions mentioned here. In JavaScript, how to conditionally add a member to an object?

But I can't spread as per the answers considering I am adding the a,b,c values in the component itself.
And other answers in here involves adding an object first.

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

0

The best way to do that is separate props.

<Button a={1} b={2} c={3} d={booleanValue && 4} />

// or
<Button data={{a:1,b:2,c:3}} optionalData={booleanValue && {d:4}} />

But, if you need to keep a single data prop.

<Button
  data={{
    a: 1,
    b: 2,
    c: 3,
    ...booleanValue ? { d: 4 } : undefined,

  }}
/>
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