Conditional Rendering React
Overview
React allows you to build distinct components that include the required behavior. Depending on the status of your application, you can only render part of them at that point. Conditional rendering in React works similarly to conditions in JavaScript. React updates the UI according to the matched condition.
Introduction to React Conditional Rendering
To be a great front-end developer, you must constantly improve your code-writing abilities and understanding of various approaches to the same task. No matter your level of experience as a developer—junior, mid-level, or senior—you must be open-minded and eager to learn new practices because what you used to know four years ago might not be a good idea now.
We have the freedom to control data in our applications since conditional expressions allow us to execute multiple tasks based on different criteria. Conditional rendering in React describes the process of providing and displaying components in response to specific conditions. They can be used to:
- alter the user interface (UI) for users based on their responsibilities, such as paid user, logged-out user, administrator, etc.
- show or update specific elements per data retrieved
- many elements can be hidden or seen, etc.
Pre-requisites
- It is recommended to have prior knowledge of the variables and functions in JavaScript.
- You must know how to import, export, and render React components.
- Node.js must be installed locally.
Ways to Implement Conditional Rendering in React Applications
In this section, we will set up a sample project to understand the usage of different ways to implement conditional rendering in React applications.
Let's take an example of an application that demands a user to log in. If the user is currently logged out, a Login button will be displayed and It will show a Logout button if the user is currently logged in.
To develop a React app, start by using create-react-app:
Navigate to the project directory:
Launch your code editor and then open the App.js file. Then replace the code with these lines:
Next, launch your code editor and open the App.css file and replace the following code with these lines:
Execute the code from the terminal window after that:
And use your browser to interact with the application. Now, let's add the necessary components to the application.
This code will serve as the foundation for all conditional rendering strategies. To revert changes as you move through this course, you might want to perform a git commit now.
We'll develop a component with a view and edit feature to show how all these techniques operate and examine conditional rendering strategies.
Output
Using an if…else Statement
When the specified condition is met, an if...else statement will perform the actions provided in the if block. If not, the else block's commands will be carried out.
You can render dynamic values in your application using JavaScript code and markup when using the JSX framework. Curly braces {} are used by JSX to denote expressions that must be interpreted before rendering. However, there is a restriction on what may be accomplished within such braces. Let's think about what would happen if you attempted to utilize an if...else statement in the render() method:
One property will be used for saving the text and another for editing the text. Add some text handling methods after that, save the changes, and then update the events as follows:
Next, for the render method, look at the mode state property to render either an edit button or a text box and a save button with the saved text:
Here's the complete code:
The simplest solution is an if...else block, however as you are aware, this is not a proper implementation. Although every coder is familiar with how it operates and it works well for straightforward use cases, there is a lot of repetition and the render method appears packed.
To make things easier to understand, let's separate all the conditional logic into two render methods—one to render the input box and the other to render the button:
Here's the complete code:
Consider the scenario when multiple branches rely on the same variable to determine the condition. You might think about employing a larger if...else block, as shown in the following code:
Using a switch Statement
As was previously demonstrated, you can use an if...else expression to conditionally return various markups from a component depending on given conditions. A switch statement that allows you to define the markup for different conditions might be used to accomplish the same thing. Although the switch statement might improve clarity a little, it is still overly verbose and ineffective when dealing with several or distinct conditions. You can't use a switch statement within a return statement in JSX, very much like an if...else statement, unless you utilize immediately invoked functions.
Using Element Variables
Let's try a different example now, where a React application shows a Login and a Logout button. You want just one of these buttons to be shown.
Output
Explanation:
Element variables resemble how conditional rendering is extracted from a function. JSX elements are stored in element variables. These variables allow you to conditionally assign elements or components outside of JSX and only render the variable inside JSX.
This is how the application will be rewritten:
AuthButton is conditionally assigned values (components) by this code so that it can later be referenced in the JSX.
Using Ternary Operators
The only JavaScript operator that accepts three operands is the conditional (ternary) operator. The if statement is typically shortened when using this operator.
This is how the application may be rewritten:
For simple if...else analyses, the ternary technique is helpful. As a project develops, it might have an impact on readability for complex comparisons and components.
Using Logical &&
To make sure there are no unintended consequences when evaluating the operands in an expression, short circuit evaluation is a method that needs to be utilized. The logical operators && allow you to declare that a particular operation should only be carried out under a specific circumstance and not at all.
This is how the application may be rewritten:
If isLoggedIn is true, this code will display the Logout button; else, nothing will be displayed. This is not advised, though, as there are other, cleaner ways to accomplish the same result. This excessive short circuit way usage could get complicated and confusing as your application develops.
Using Immediately Invoked Function Expressions
It was mentioned in earlier parts that JSX has constraints that prevent it from running all JavaScript code. These restrictions are overcome through IFFEs. Immediately Invoked Function Expressions (IFFEs) is a JavaScript function that is called as soon as it is defined:
Syntax:
By using this method, conditional logic may be written directly in JSX and then wrapped in an anonymous function that is called as soon as the code is evaluated.
This is how the application may be rewritten:
Using an arrow function, the following can be written in a little more concise way:
Using Enhanced JSX Libraries
Certain libraries expose capabilities to extend JSX, allowing conditional rendering to be implemented directly with JSX. JSX Control Statements is one of these libraries. It is a Babel plugin that, during transpilation, converts component-like control statements into JavaScript counterparts.
The application could be rewritten as follows once the babel-plugin-jsx-control-statements package has been installed and your Babel configuration has been modified:
The code you write will eventually be converted to a regular JavaScript conditional, thus this method is not advised. It is usually always preferable to write JavaScript directly rather than adding a second dependent on something so unimportant.
Selecting a Conditional Rendering Approach
Generally speaking, it's best to make sure that when using conditional rendering you:
- To avoid components unmounting and remounting unnecessarily, do not change the positions of components randomly.
- Only the markup that the conditional rendering effects should be changed.
- Do not unnecessarily bloat your component inside the render method because this causes components to render more slowly.
You should take into account:
- The percentage of markup that will be conditionally rendered.
- The number of potential outcomes
- Which would be easier to understand and read
The following suggestions should be kept in mind generally:
- The short circuit evaluation may be most appropriate in circumstances where there is just one expected result.
- When there are two predicted outcomes, an if...else expression, element variable, ternary operator, or immediately invoked function expression is typically the best choice.
- When there are more than two results, a switch expression, extracted function, or extracted functional component is typically the best option.
Note: Remember that these are suggestions, not rules. You may have to choose methods that do not adhere to these suggestions because of the requirements and standards of your project.
Conclusion
- Conditional rendering refers to the ability to render distinct user interface (UI) markup based on whether a condition is true or false.
- React gives us the option to render several elements or components according to a condition.
- This article covered the seven different approaches to implementing conditional rendering in React apps.
- Each approach has a benefit of its own, and the use case mostly determines which approach is used.
- The first approach is using an if...else statement which executes the if block if true. If not, the else block's commands will be carried out.
- A switch statement is similar to an if...else statement that allows you to define the markup for different conditions.
- Element variables allow you to conditionally assign elements or components outside of JSX and only render the variable inside JSX.
- The only JavaScript operator that accepts three operands is the conditional (ternary) operator. The if statement is shortened using this operator.
- The logical operator && is used when a particular operation should only be carried out under a specific circumstance and not at all.
- In Immediately Invoked Function Expressions (IFFEs) the conditional logic may be written directly in JSX and then wrapped in an anonymous function that is called as soon as the code is evaluated.