React.js lets you create different components, and each of them encapsulates several lifecycle methods. The lifecycle methods maintain or control the behavior of that component. You can render components depending on the application state.
If you are rendering certain components and elements with any condition, then the process is called Conditional Rendering.
This article covers the different methods used to implement Conditional Rendering in React.js.
Conditional rendering works in a similar way condition works in JavaScript. You can use JavaScript operators like if/else for updating UI on state changes.
For example:
1function UserLoggedIn(props) { 2 return <div> 3 <h1>Welcome back! </h1> 4 <span>Log out </span> 5 </div>; 6} 7
1function UserLoggedOut(props) { 2 return <div> 3 <h1>Sign in, please! </h1> 4 <span>Log out </span> 5 </div>; 6}
When the user login status changes we must have a component to handle it. The LoggedStatus component displays either of LoggedIn and LoggedOut components based on the boolean value shown below.
1function LoggedStatus(props) { 2 const isUserLoggedIn = props.isUserLoggedIn; 3 if (isUserLoggedIn) { 4 return <UserLoggedIn />; 5 } 6 7else { 8 9return <UserLoggedOut />; 10 } 11 12} 13ReactDOM.render( 14 <LoggedStatus isUserLoggedIn={false} />, 15 document.getElementById('root') 16); 17
Similar to if statements we can use switch statements for conditional rendering. Get the switch statement out of render in the function and then call it by passing the params.
1renderSwitch(param) { 2 switch(param) { 3 case 'foo': 4 return 'bar'; 5 default: 6 return 'foo'; 7 } 8} 9 10render() { 11 return ( 12 <div> 13 {this.renderSwitch(param)} 14 </div> 15 ); 16} 17
Also, you can inline the “switch” in the render function. In the below example we can see the implementation of a switch-like expression using a plain old JavaScript object:
Example:
1render ( ) { 2 return ( 3 <div> 4 5 { 6 { 7 'foo': <Foo />, 8 'bar': <Bar /> 9 }[param] 10 } 11 12 </div> 13 ) 14} 15
Element variables hold JSX elements and only render the variables within JSX. You can conditionally assign elements or components to these variables but only outside the JSX and render the variable within JSX.
It is used to avoid the repeating return statement in the render( ) method. Use a variable to store the JSX element and initialize it when the condition is true.
For Example:
1class ConditionalRendering extends React.Component{ 2 constructor(props){ 3 super(props); 4 this.state ={ 5 isLoggedIn : true 6 } 7 } 8 9 render(){ 10 let message; 11 if(this.state.isLoggedIn){ 12 message = <div>Welcome User </div>; 13 } 14 else{ 15 message = <div>You need to login</div>; 16 } 17 18 return message; 19 }; 20} 21export default ConditionalRendering; 22
If you don’t want to use the if … else block, you can use a ternary operator instead. The ternary operator takes three operands and the syntax is:
Syntax: condition? expression_if_true : expression_if_false
The expression can contain JSX, which can be applied to the different parts of components.
1class ConditionalRendering extends React.Component{ 2 constructor(props){ 3 super(props); 4 this.state ={ 5 isLoggedIn : true 6 } 7 } 8 9 render(){ 10 return this.state.isLoggedIn? <div> Welcome! </div> : ""; 11 }; 12} 13export default ConditionalRendering; 14
It is a special case and simplified version of the ternary operator with && operator. The && operator evaluates the left side expression to generate the result, unlike the & operator which evaluates the right side of the expression first. It is useful if you want to render either something or nothing.
Example:
1class ConditionalRendering extends React.Component{ 2 constructor(props){ 3 super(props); 4 this.state ={ 5 isLoggedIn : true 6 } 7 } 8 9 render(){ 10 return this.state.isLoggedIn && <div> Welcome!</div>; 11 }; 12} 13export default ConditionalRendering; 14
IIFE provides you with a way to execute a function immediately as soon as they are created. They are very useful since they do not affect the global object and help you to easily isolate variable declarations.
Here is the syntax that define IIFE
1function TestFunc ( ) { 2 3} 4 5TestFunc ( );
We can use the function as soon as it is defined:
1(function TestFunc(/*args*/){ 2}(/*args*/));
It can be defined with arrow function as well:
1((/*args */) => { 2})(/* args */)
Implementation using arrow function:
1{(() => { 2 if (isLoggedIn) { 3 return <button>Logout</button>; 4 } else { 5 return <button>Login</button>; 6 } 7})()}
So, these are the 6 different methods for implementing conditional rendering in React. Moreover, there are certain rules you need to follow while rendering the components or elements.
Now you know how to render React components with conditional rendering. But in a few cases, you might want to hide the React.js component even though another component renders it.
This can be achieved by returning null in the render output.
Example: The following example shows how to hide and show the React.js component.
1function WarningBanner(props) { 2 if (!props.warn) { 3 return null; 4 } 5 6 return ( 7 <div className="warning"> 8 Warning! 9 </div> 10 ); 11} 12 13class Page extends React.Component { 14 constructor(props) { 15 super(props); 16 this.state = {showWarning: true}; 17 this.handleToggleClick = this.handleToggleClick.bind(this); 18 } 19 20 handleToggleClick() { 21 this.setState(state => ({ 22 showWarning: !state.showWarning 23 })); 24 } 25 26 render() { 27 return ( 28 <div> 29 <WarningBanner warn={this.state.showWarning} /> 30 <button onClick={this.handleToggleClick}> 31 {this.state.showWarning ? 'Hide' : 'Show'} 32 </button> 33 </div> 34 ); 35 } 36}
Here you can clearly see if the value of prop is false then the component will not be rendered. And returning null from the render( ) method will not affect the component’s lifecycle methods.
Well, now you know about Conditional Rendering in React.js with almost all the useful methods. Also, we have seen how to hide the component while rendering it using the render( ) method.
“Make your React app development effortless, faster, and better with DhiWise- A new edge platform that aims to improve developer’s productivity with automation.”
Explore more about DhiWise React Web Builder for faster Web application development and how it simplifies a developer’s life with its out-of-the-box functionalities.
Start using DhiWise today, sign up now!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.