Conditional rendering in React.js


Using conditional statements specific components can be rendered and removed . Conditional handling works similarly in JavaScript and React.js

Example

function DisplayUserMessage( props ){
   const user = props.user.type;
   if(type==’Player’){
      return <h1>Player </player>;
   }
   If( type==’Admin’){
      Return <h1>Admin </h1>;
   }
}

If statement is used in above example. Type of user decides which message to return.

Local state of component is useful in deciding the conditional rendering as state is flexible to change inside the component.

Inline if with logical && operator

function MessageSizeChecker(props) {
   const message = props.message;
   return (
      <div>
         <h1>Hello!</h1>
         {message.length > 100 &&
            <h2>
               Message size is greater than 100
            </h2>
         }
      </div>
   );
}

If the first argument to the && operator evaluates to true then second argument is rendered on the screen.

Inline if else with ternary operator −

Its having a syntax like condition ? ‘ first’ : ‘second’;

function MessageSizeChecker(props) {
   const message = props.message;
   return (
      <div>
         <h1>Hello!</h1>
         {message.length > 100 ? ‘Message size is greater than 100’: ‘Message size is ok’}
      </div>
   );
}

This ternary expression can be used on number of block statement but it becomes tedious to understand . So to keep it simple it should be used on simple conditions.

We can decide which component to render.

render() {
   const isPlayer = this.state.user.isPlayer;
   return (
      <div>
         { isPlayer ? (
            <Player >
            ) : (
            <Admin />
            )
         }
      </div>
   );
}

To prevent the component from rendering , we can return a null as well. But just returning null from render method does not prevent the further applicable lifecycles of React

Updated on: 28-Aug-2019

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements