Original address: https://scotch.io/tutorials/7-ways-to-implement-conditional-rendering-in-react-applications
With React, we can build dynamic and highly interactive single-page applications, and one way to take full advantage of this interaction is through conditional rendering.
Catalog
The term conditional rendering describes the ability to render different UI tags based on certain conditions.In React documents, this is a way to render different elements or components based on conditions.This concept is often applied in the following situations:
- Rendering external data from API
- Show/Hide Elements
- Switch Application Functions
- Implement permission levels
- Authentication and Authorization
In this article, we will explore seven ways to achieve conditional rendering in React applications.
Challenge
First, depending on the value of isLoggedIn in the component state, we want to be able to display the Login button when the user is not logged in and the Logout button when the user is logged in.
The following is a screenshot of our initial components:
The code is as follows:
import React, { Component } from "react"; import ReactDOM from "react-dom"; import "./styles.css"; class App extends Component { constructor(props) { super(props); this.state = { isLoggedIn: true }; } render() { return ( <div className="App"> <h1> This is a Demo showing several ways to implement Conditional Rendering in React. </h1> <button>Login</button> <button>Logout</button> </div> ); } } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);
Online testing: CodeSandBox
Solution
In the code snippet,...Represents some code that is not directly related to the point being interpreted.
1. Use if...else statement
Use if...The else statement allows us to point out that if the condition is true, a specific action is performed, otherwise other actions are performed.Using the example, I will test if...Else is commonly used for two methods of conditional rendering in React.
- Extract conditional rendering into a function
In JSX, we can put JS code and HTML tags together to ensure amazing interactivity within the program.To do this, we use braces {} and write our JS in them.But there is a limit to what you can do in parentheses.For example, the results of the code below do not achieve what we want.
// index.js ... render() { let {isLoggedIn} = this.state; return ( <div className="App"> <h1> This is a Demo showing several ways to implement Conditional Rendering in React. </h1> { if(isLoggedIn){ return <button>Logout</button> } else{ return <button>Login</button> } } </div> ); } ...
For more information, visit This link.
To solve this problem, we extract conditional logic into a function as follows:
// index.js ... render() { let {isLoggedIn} = this.state; const renderAuthButton = ()=>{ if(isLoggedIn){ return <button>Logout</button> } else{ return <button>Login</button> } } return ( <div className="App"> <h1> This is a Demo showing several ways to implement Conditional Rendering in React. </h1> {renderAuthButton()} </div> ); } ...
Notice that we extracted the logic from JSX into the function renderAuthButton.Therefore, we only need to execute functions within JSX braces.
- Multiple return statements
When using this method, components must be as simple as possible to avoid the re-rendering of sibling or parent components.So we created a new component called AuthButton.
// AuthButton.js import React from "react"; const AuthButton = props => { let { isLoggedIn } = props; if (isLoggedIn) { return <button>Logout</button>; } else { return <button>Login</button>; } }; export default AuthButton;
AuthButton returns different elements and components based on the state value passed in through the component property isLoggedIn.Therefore, we import it into index.js and pass in the status values as follows:
// index.js ... import AuthButton from "./AuthButton"; ... render() { let { isLoggedIn } = this.state; return ( <div className="App"> ... <AuthButton isLoggedIn={isLoggedIn} /> </div> ); } ...
Be sure to avoid the following:
// index.js ... render() { let { isLoggedIn } = this.state; if (isLoggedIn) { return ( <div className="App"> <h1> This is a Demo showing several ways to implement Conditional Rendering in React. </h1> <button>Logout</button>; </div> ); } else { return ( <div className="App"> <h1> This is a Demo showing several ways to implement Conditional Rendering in React. </h1> <button>Login</button> </div> ); } } ...
Although the above code will achieve the same results, it will unnecessarily bloat components and cause performance problems as a result of constantly re-rendering an unchanged component.
2. Use element variables
Element variables are an extension of the extraction of conditional rendering into a function described above.Element variables are simply variables that hold JSX elements.Therefore, we can assign elements/components to these variables conditionally outside of JSX, just by rendering them in JSX.
// index.js ... render() { let { isLoggedIn } = this.state; let AuthButton; if (isLoggedIn) { AuthButton = <button>Logout</button>; } else { AuthButton = <button>Login</button>; } return ( <div className="App"> <h1> This is a Demo showing several ways to implement Conditional Rendering in React. </h1> {AuthButton} </div> ); } ...
Notice how we conditionally assign values (components) to AuthButton, and then we just need to render it in JSX.
3. Use switch statements
As shown earlier, we can use if...The else statement returns different labels from the component based on the conditions set.The same effect can be achieved with the switch statement, in which we can specify labels for different conditions.Look at the following code:
// AuthButton.js import React from "react"; const AuthButton = props => { let { isLoggedIn } = props; switch (isLoggedIn) { case true: return <button>Logout</button>; break; case false: return <button>Login</button>; break; default: return null; } }; export default AuthButton;
Notice how we return different buttons based on the value of isLoggedIn.This method is more reasonable when there are more than two possible values or results.You can also cancel with a break statement, just as the return statement automatically terminates execution.
Note: Returning null from a component hides itself/does not show anything.This is a good way to switch component visibility.
4. Ternary Operators
If you are familiar with ternary operators, you should know that this is a simpler way to write if statements.So we might write as follows:
// index.js ... render() { let { isLoggedIn } = this.state; return ( <div className="App"> <h1> This is a Demo showing several ways to implement Conditional Rendering in React. </h1> {isLoggedIn ? <button>Logout</button> : <button>Login</button>} </div> ); } ...
In the example above, however, this method can make components bulky, bulky and difficult to understand, and you can encapsulate the conditions in pure function components.As follows:
// AuthButton.js import React from "react"; const AuthButton = props => { let { isLoggedIn } = props; return isLoggedIn ? <button>Logout</button> : <button>Login</button>; }; export default AuthButton;
5. Logical Operators &&
Short-circuit operation is a technique used to ensure that there are no side effects in the expression operation.Logic &&Help US specify that only one case should be executed, otherwise it will be completely ignored.This is useful in situations where only certain conditions need to be executed when they are true.
For example, if we are logged in, we only need to show the Logout button, otherwise we will do nothing.The following:
// index.js ... render() { let { isLoggedIn } = this.state; return ( <div className="App"> <h1> This is a Demo showing several ways to implement Conditional Rendering in React. </h1> {isLoggedIn && <button>Logout</button>} </div> ); } ...
If isLoggedIn is true, the Logout button will be displayed, otherwise nothing will be displayed.We can achieve the final result in the same way, as shown below.
// index.js ... return ( <div className="App"> <h1> This is a Demo showing several ways to implement Conditional Rendering in React. </h1> {isLoggedIn && <button>Logout</button>} {!isLoggedIn && <button>Login</button>} </div> ); ...
This is the correct button to render based on the value of isLoggedIn.However, this is not recommended because better, cleaner methods can achieve the same results.Also, once the component is a little larger, it can easily make your code look confusing and difficult to understand.
6. Use the Immediate Call Function Expression (IIFE)
Remember the limitations of JSX you just mentioned, in which you can't execute all JavaScript code.Well, this is not entirely correct, because there are many ways to bypass this behavior.One way is to use IIFE.
(function () { statements })();
click link Learn more
With this technique, we can write conditional logic directly in JSX, but wrap it in an anonymous function that is called immediately after running this part of the code.See the following example:
//index.js ... render() { let { isLoggedIn } = this.state; return ( <div className="App"> <h1> This is a Demo showing several ways to implement Conditional Rendering in React. </h1> {(function() { if (isLoggedIn) { return <button>Logout</button>; } else { return <button>Login</button>; } })()} </div> ); } ...
You can also use the arrow function to write the code in a more concise way, as follows:
// index.js ... return ( <div className="App"> <h1> This is a Demo showing several ways to implement Conditional Rendering in React. </h1> {(()=> { if (isLoggedIn) { return <button>Logout</button>; } else { return <button>Login</button>; } })()} </div> ); ...
7. Use enhanced JSX
Some libraries expose the ability to extend JSX, so conditional rendering can be achieved directly with JSX.One of these libraries is JSX Control Statements .It is a Babel plug-in that converts control statements like components into JavaScript statements during compilation.See the example below to learn how.
// index.js ... return ( <div className="App"> <h1> This is a Demo showing several ways to implement Conditional Rendering in React. </h1> <Choose> <When condition={isLoggedIn}> <button>Logout</button>; </When> <When condition={!isLoggedIn}> <button>Login</button>; </When> </Choose> </div> ); ...
However, this is not recommended because the code you write will eventually convert to regular JavaScript conditions.Writing JavaScript alone may always be better than adding extra dependency on such trivial things.
Performance issues
As a general rule, it is best to ensure that when conditional rendering is implemented:
- Do not change the location of components at will to prevent unnecessary uninstallation and overloading of components.
- Change only the labels associated with conditional rendering, not the unchanged parts of the component.
- Do not unnecessarily bloat components in render methods, which can cause them to delay rendering.
summary
We have successfully studied seven ways to achieve conditional rendering in React.Each method has its own advantages, and choosing which one depends on the actual situation.Things to consider include:
- Size of conditional rendering labels
- Number of possible results
- Which is more intuitive and readable
In general, I recommend:
- When there is only one expected result, it is convenient to use the logical & operator.
- For Boolean cases or cases where there are only two possible outcomes, you can use if...else, Element variable, ternary operator, and IIFE.
- If the result is more than two, you can use the Switch statement to extract it as a function or as a pure function component.
However, these are only suggestions, but ultimately they are based on the actual situation.