Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!