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

154
Visualizações
React Structure: Avoiding multiple ternary operators

Within a component I'm attempting to "hide" and "show" elements as a user clicks through content. I was told ternary operators are the way to do this. However now it's getting far more complicated / messy due to nested ternary operators.

Is this the correct approach in React or is there a better way?

Example:

const [compltedWaveOne, setcompltedWaveOne] = useState(false);
const [compltedWaveTwo, setcompltedWaveTwo] = useState(false);
const [compltedWaveThree, setcompltedWaveThree] = useState(false);
const [compltedWaveFour, setcompltedWaveFour] = useState(false);
   
  {compltedWaveOne ?
  ...Large amount of content 
  : //else 
  ...Large amount of content 
  }

  ... Now I need more content here if completedWaveTwo is true etc. Also need to hide the other content 
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

  1. Ternary operators are great IMO, but they get messy once you start nesting. That is why you wanna do something like this:

    if(compltedWaveOne) {
      return ([CONTENT]) // you can use your ternary op. here
    } else {
      return ([CONTENT])
    }
    
  2. I would recommend better naming conventions rather than compltedWaveOne

  3. Your useState is not valid since you name both variables the same.

    Stick to this type of convention:

    const [state, setState] = useState()
    
about 4 years ago · Juan Pablo Isaza Relatório

0

Rather than using multiple state, you could simply use an array and map with respect to the component.

const WavesComponents = [Wave1, Wave2, Wave3, Wave4, Wave5];

function _App() {
  const [waves, setCompletedWaves] = useState([0, 0, 0, 0, 0]);

  function toggleCompletion(idx) {
    setCompletedWaves(prev => {
      prev.slice();
      prev[idx] = !prev[idx];
      return prev;
    });
  }

  const WaveComponent = WavesComponents[waves];
  return <WaveComponent data={} />;
}

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