Front-end web development with ReactJS remained a hot trend in 2020 and is continuing its popularity till now. According to Statista, it is the most used framework among developers worldwide in 2021. If you also prefer ReactJS over other frameworks, enjoy this article; it covers various methods to implement conditional rendering in ReactJS to help you achieve more readable codes.
While developing an application in ReactJS or any other JavaScript library, it is common to deliver elements and components based on certain conditions. This process of providing components as per the use case in hand is called conditional rendering in ReactJS.
Let’s understand this with an example of handling a login and logout button. There will be separate components for both buttons as both have different functions.
Now take the case-
In both these situations, we have to render components as per the requirement to display the correct message to users. That is why conditional rendering in ReactJS is used to simplify the code.
In ReactJS, there are various ways to do conditional rendering. Depending upon the problem you want to solve, some are best suited than others. When hiring ReactJS developers, always ensure they apply conditional rendering in the below-given scenarios to deliver more scalable applications.
Let’s move on to discover the comprehensive list of conditional rendering in ReactJS withpractices for these patterns.
Let’s dive deeper into all these conditional rendering options in ReactJS and see when and how to apply them.
Using the ‘if’ statement is the most basic conditional rendering logic in ReactJS. We use the “if” statement when we want to render different components in different situations.
Let’s understand this with an example.
Suppose we want to deliver different messages whenever a user login or logout. For that, we create two functional elements those are:
One element returns the message ‘ Hello Everyone.”
const HelloEveryone = (props) => { return <h1>Hello Everyone!</h1>; Another display the message ‘Welcome you.’ Const WelcomeMessage = (props) => { return <h1> Welcome you.</h1>; |
Now, to check if the user is logged in and ensure the right message is displayed, we will create a third functional component using the “if” statement, wherein we will take the above two components.
const IsUserLoggedIn = (props) = > { const isLoggedIn = props.isLoggedIn; If (isLoggedIn) { return <HelloEveryone />; } return <WelcomeMessage />; } ReactDOM.render( <IsUserLoggedIn isLoggedIn={false} />, document.getElementById(‘root’) ); |
If we want to render a component only when a specific action will happen, this can be done using the “if-else” statement.
See how we use the “if-else” statement in the below example. Only when the user is logged in( specific action) the logout button will render, while in all other cases, the login button will display.
render () { let {UserIsLoggedIn} = this.state; const renderAuthButton = () =>{ if(UserIsLoggedIn) { return <button>Logout</button> } else { return <button>Login</button> } } |
The ternary operator is another way of doingan “if-else” statement but in a shorter form. Here the first part states the state condition, and if it is true, the second part is returned, else the third part is returned. Let’s check how it is done:
const IsUserLoggedIn = (props) => { const isLoggedIn = props.isLoggedIn; return ( <div> {isLoggedIn ? ( “You are logged in!” ) : ( “You are logged out!” )} </div> ); } ReactDOM.render( <IsUserLoggedIn isLoggedIn={false} />, document.getElementById(‘root’) ); |
In the ternary operator, the parentheses () around both the implicit return statements allow you to return single or multiple components from there. But in the case of a single element, you can omit the parentheses.
The switch case conditional rendering in ReactJS is used for one of the below-given reasons:
These reasons depict that we should use a “switch case” conditional rendering when rendering multiple components. Now, to understand it more precisely, let’s take a situation of notification component rendering warning, error, and info component on the basis of status string. Now see how to write code using the “IF” statement and the “switch case” in this situation.
Using “If” conditional rendering we write the code as:
function Notification({ text, status }) { if (status === ‘info’) { return <Info text={text} />; } if (status === ‘warning’) { return <Warning text={text} />; } if (status === ‘error’) { return <Error text={text} />; } return null; |
Using switch case conditional rendering, we write the code as:
function Notification({ text, status }) { switch (status) { case ‘info’: return <Info text={text} />; case ‘warning’: return <Warning text={text} />; case ‘error’: return <Error text={text} />; default: return null; } } |
ReactJS components always have to return an element or null; hence it is advisable to use the default for the switch case operator.
Although the switch case is a wonderful option for multiple conditional rendering in the ReactJS, it has one drawback: we can not use the switch case with JSX. To overcome this drawback, ‘Multiple Conditional Rendering with Enum’ comes into action.
In JavaScript, when an object is used as a map of key-value pairs, it is called an enum. An enum is the best way to handle the conditional rendering of multiple components as it can be used within the JSX.
To explain how to use an enum, we will take the same example of the notification component. Here we used enum as an inlined object (Inner curly braces)
function Notification({ text, status }) { return ( <div> { { info: <Info text={text} />, warning: <Warning text={text} />, error: <Error text={text} />, }[status] } </div> ); } |
We can also use enum as a constant for condition render and a function to retrieve the value. Have a look at both the situation
Enum as a constant for conditional rendering
Const NOTIFICATION_STATES ={ Info: <Info />, Warning: <Warning />, Error: <Error />, }; function Notification({ status }) { return ( <div> function Notification({ status }) { return ( <div> {NOTIFICATION_STATES [status]} </div> ); } |
Creating Enum component which will pass the value of the state to the function(enum state)
class Enum extends React.Component { render() { return ( <div> <h1>Conditional Rendering with enums</h1> <EnumState state=”default”></EnumState> <EnumState state=”bar”></EnumState> <EnumState state=”foo”></EnumState> </div> ); } } ReactDOM.render(<Enum />, document.getElementById(“app”)); |
Logical && operator is used for checking the condition. It will render the element right after && if the condition is true. While if the condition is false, ReactJS will skip it.
Refer to the below example to understand the behaviours of && operator
(‘welcomehome’ == ‘WelcomeHome’) && alert(‘This alert will never be shown!’)
If you run the above code, the alert message will not be displayed as the condition is not matching.
But you will see the alert message if you run the below code
(5 > 4) && alert(‘This alert will be shown!’)
import React from ‘react’; import ReactDOM from ‘react-dom’; // Example Component function Example() { return(<div> { (10 > 5) && alert(‘This alert will be shown!’) } </div> ); } |
After looking at these components, we can say that Logical && operator gives more concise results than a ternary operator. That’s why it is also called ‘short circuit evaluation’.
Higher-Order components or HOCs is a function that takes a component and returns it with some added functionality. We can use it for multiple use cases. Out of them, one of the crucial use cases is to change the look of a component with conditional rendering.
Look at the HOC in the below given example, which shows either a desired component or a loading indicator.
// HOC declaration function withLoading(Component) { return function EnhancedComponent({ isLoading, …props }) { if (!isLoading) { return <Component { …props } />; } return <div><p>Loading…</p></div>; }; } // Usage const ListWithLoading= withLoading(List); <ListWithLoading isLoading={props.isLoading} list={props.list} /> |
In this article, we have covered multiple ways to do conditional rendering in ReactJS. Each method has its own advantages and helps to achieve more readable code. Depending upon your use case at hand, choose the method which is the best fit for your situation. We believe this article will help simplify your decision; perhaps we are eager to listen to your opinion and suggestions, do reply in the comment section.
Namaste UI collaborates closely with clients to develop tailored guest posting strategies that align with their unique goals and target audiences. Their commitment to delivering high-quality, niche-specific content ensures that each guest post not only meets but exceeds the expectations of both clients and the hosting platforms. Connect with us on social media for the latest updates on guest posting trends, outreach strategies, and digital marketing tips. For any types of guest posting services, contact us on info[at]namasteui.com.
If you are in a financial crisis , or need to start a new business…
Hormonal balance plays a pivotal role in overall well-being, influencing various aspects of health, from…
Dog walking is an excellent way to maintain your furry friend's camaraderie and provides many…
Introduction Businesses understand the diverse requirements of mobile applications, which provide a competitive advantage. There…
The Internet of Things (IoT) has recently changed the world. It links gadgets together and…
NFTs, or Non-Fungible Tokens, are revolutionizing the digital economy. These unique digital assets, authenticated through…