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

88
Visualizações
Conditionally mapping two different arrays into a React component depending on boolean value

I currently have an array called options which is mapped into a React component like so:

{options.map((option) => (
   <Component key={option.code}></Component>
))}

However, I am trying to expand my component so that if a boolean value: shouldCount is true, then the optionsWithCount array is passed to the component instead of the options array. The component above has a lot more props etc than shown so I'd like to avoid just repeating the component with all of its props if possible.

Can anyone suggest a possible way of going about this?

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

0

Would using a utils function getOptions() work? It would take in the shouldCount flag as input and return the desired array. Example:

{ 
  getOptions(shouldCount).map((option) => (
    <Component key={option.code}></Component>
  ));
}

const getOptions = (shouldCount) => {
  return shouldCount ? optionsWithCount : options;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You can update the options variable conditionally so you don't have to rewrite the same code again.

Make options a state;

const [options, setOptions] = useState([])

And use useEffect to update it;

useEffect(()=>{
    if(shouldCount) setOptions([1,2,3,4,5])
    else setOptions([5,6,7,8,9])
}, [shouldCount])

So that way, when shouldCount changed it will trigger useEffect and change optinos values.

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