React JS Conditional Rendering

We have to Show or Hide some html code based on condition. There are four types of different approaches to doing this. 1. if/else 2. Element variable 3. Ternary conditional operator 4. Short circuit operator

We can get more ideas by looking below example. you can put this file in /src/components folder and put in /src/App.js file.

1. if/else

Example
import React, { Component } from 'react'; import ChildComponent from './components/ChildComponent'; class ConditionalComponent extends Component { constructor(props) { super(props) this.state = { isAllowed: false } } render() { if(this.state.isAllowed){ return( <div> <div>You are allowed</div> </div> ) }else{ return( <div> <div>You are not allowed</div> </div> ) } } } export default ConditionalComponent;

In above code, it is showing in browser 'You are not allowed'. when we change state isAllowed to true then it will show in browser 'You are allowed'.

2. Element variable

Example
class ConditionalComponent extends Component { constructor(props) { super(props) this.state = { isAllowed: false } } render() { let message; if(this.state.isAllowed){ message = <div>You are allowed</div> }else{ message = <div>You are not allowed</div> } return <div>{message}</div> } }

In this approach we take html based on condition in a variable message, then return this message to render.

3. Ternary conditional operator

Example
class ConditionalComponent extends Component { constructor(props) { super(props) this.state = { isAllowed: false } } render() { return this.state.isAllowed ? ( <div> <div>You are allowed</div> </div> ) : ( <div> <div>You are not allowed</div> </div> ) } }

In this approch we ternary condition in jsx return. this approch is used most of the time because it keeps the code simple and less crowded.

4. Short circuit operator

This approch is used for either we have to render something or nothing. this approch don't have else part.

Example
class ConditionalComponent extends Component { constructor(props) { super(props) this.state = { isAllowed: false } } render() { return this.state.isAllowed && ( <div> <div>You are allowed</div> </div> ) } }

In this approach if isAllowed is true then it will show text on browser else it will show nothing in browser.

As per above example we can render html code on condition based on our requirement.

 

← Previous

Next →