How to use if else statements inside React JSX

There are several different ways to use the conditional if else statements inside the JSX of a React component.

The method I use the most is that I create a self invoking function and inside that function I write my logic. Here is a quick example

<div>
 {(() => {
  if(a == true){
   return (      
    <span>A is TRUE</span>
   );
  }else{
   return (    
    <span>A is FALSE</span>
   );
  }
 })()}
</div>

The great thing about this method is that it is very easy to read and you can write complex login in there. The disadvantage is that it is very verbose and may affect the performance of your components since we are creating and calling a new function on every render. You can also extract the self invoking function into a new component function and call it from there.

class Test extends React.Component {
 constructor(props){
  super(props);
  this.state = {
   a : true
  };
  this.customLogicMethod = this.customLogicMethod.bind(this);
 }
 customLogicMethod(){
  let { a } = this.state;
  if(a == true){ 
   return ( <span>A is TRUE</span> ); 
  }else{ 
   return ( <span>A is FALSE<span/> ); 
  }
 }
 render(){
  return (
   <div>
    {this.customLogicMethod()}
   </div>
  );
 }
}

The second method is for occasions when you have very small if else logic.

return (
 <div>
  {(a == true) ? <span>A is TRUE</span> : <span>A is FALSE</span> }
 </div>
 );

Leave a Reply