Search code examples
javascriptreactjsconditional-statementsreturn

React nested conditional rendering in return


I have the following code

return (
  
  <Container>
    
    {param1==false && param2==false &&(
      <CustomComponent> 
      </CustomComponent>
      )}
      
    {param1 == false && param2==true &&( 
      <CustomComponent2> 
      </CustomComponent2>
      )}
      
    <Container>  
    </Container>

  </Container>
);

The problem right now is the <Container> component is still being rendered after the custom component checks have been made, which makes sense.

I want it so only 1 component is rendered ( either custom, custom2 or just the container ) from the docs here - https://react.dev/learn/conditional-rendering#conditionally-returning-jsx I know you can use ternary operator to conditionally render components but I have 3 cases to check not 2.

Now I could do nested ternary operators but that is not readable so I would like to know an alternative !


Solution

  •     you can check a multiple conditions in ternary operator
         like this
        
        return (
    <>
         <Container>
            {param1==false && param2==false ?
              <CustomComponent> 
              </CustomComponent> :
               param1 == false && param2==true ? 
               <CustomComponent2>     
               </CustomComponent2> :
            <Container>  
            </Container>
           }  
     </Container>
    </>
    );