Search code examples
reactjscoding-style

Conditonal Rendering of components


I find myself writing code like this quite frequently, to avoid deeply nested statements to determine return values e.g.:

function Warning(props){
   return <h1> Warning! </h1>
}
 
function SomeComponent(props){
   const [showAtTop, setShowAtTop] = useState(false); 
    
   //...

   const ShowWarningAtTop = showAtTop
      ? <Warning></Warning>
      : null
   const ShowAtBottom = showAtTop
      ? null
      : <Warning></Warning>


   return <div>
      {showWarningAtTop}
      <div> Main Content</div>
      {showWarningAtBottom}
   </div>
}

I'm not 100% satisfied with that solution, (repetetive code, return statement gets somewhat bloated and it's quite hard to look at the return statement to see whats happening) and i'm anxious that it's considered bad style. Is there a more readable / cleaner way to do this?


Solution

  • Shorter/simpler conditional rendering using logical AND (&&).

    Inline If with Logical && Operator

    React ignores booleans in output. Only react components need to return null to indicate they are rendering nothing, anything within a component can return true/false and react will ignore and not render the literal value.

    You can also self-close empty tags in JSX.

    function SomeComponent(props){
       const [showAtTop, setShowAtTop] = useState(false); 
        
       //...
    
       return (
         <div>
           {showAtTop && <Warning />}
           <div> Main Content</div>
           {showAtTop && <Warning />}
         </div>
       );
    }