Home > front end >  React Structure: Avoiding multiple ternary operators
React Structure: Avoiding multiple ternary operators

Time:04-09

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 

CodePudding user response:

  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()
    

CodePudding user response:

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={} />;
}

  • Related