How to use conditional rendering to display different content in React?
Conditional rendering is a very important concept when we are developing modern web applications.
In React, conditional rendering helps us to render components selectively based on different conditions. This allows our applications to dynamically display different content when users' operations and application states change.
This article will dive into how to use conditional rendering effectively in React and provide some sample code to help you better understand the concept.
1. Basic concepts of conditional rendering
Conditional rendering refers to determining whether to display a certain component based on a certain condition.
For example, you may want to display different content based on the user's login status, or display a load indicator in a certain state, etc.
In React, conditional rendering is usually combined with conditional statements in JavaScript, such asif
Statements, ternary operators, etc. to implement.
2. Use if statement for conditional rendering
The easiest way to render conditionally is to useif
Statement.
In the component's render method, you can use it according to the state or attributeif
Statements to decide which part to render.
Sample code:
Here is a useif
An example of a statement for conditional rendering.
This example shows a simple user login interface that displays different contents depending on whether the user is logged in or not.
import React, { useState } from 'react'; const LoginControl = () => { const [isLoggedIn, setIsLoggedIn] = useState(false); const handleLogin = () => { setIsLoggedIn(true); }; const handleLogout = () => { setIsLoggedIn(false); }; let button; if (isLoggedIn) { button = <button onClick={handleLogout}>Logout</button>; } else { button = <button onClick={handleLogin}>Login</button>; } return ( <div> <h1>{isLoggedIn ? 'Welcome Back!' : 'Please Log In'}</h1> {button} </div> ); }; export default LoginControl;
In this example, we useisLoggedIn
Status to determine whether the component should display "Welcome back" or "Please log in" and render different buttons in different states.
3. Conditional rendering using ternary operators
Another common pattern is conditional rendering using ternary operators.
This method is often used to render simpler UIs, which makes the code more concise.
Sample code:
Here is an example using a ternary operator that covers scenarios that display a list of items or load indicators.
import React, { useState, useEffect } from 'react'; const ItemList = () => { const [isLoading, setIsLoading] = useState(true); const [items, setItems] = useState([]); useEffect(() => { setTimeout(() => { setItems(['Apple', 'Banana', 'Cherry']); setIsLoading(false); }, 2000); }, []); return ( <div> <h1>Item List</h1> {isLoading ? ( <p>Loading...</p> ) : ( <ul> {(item => ( <li key={item}>{item}</li> ))} </ul> )} </div> ); }; export default ItemList;
In this example, we useisLoading
State to simulate the process of loading data.
Before the data is loaded, the user is prompted to "Loading...", and after the loading is completed, the project list is displayed.
4. Use short-circuit operator for conditional rendering
In case, when a component needs to be displayed or nothing is rendered, the short-circuit operator (&&
) Very useful.
If the condition is true, the following elements will be rendered; if the condition is false, nothing will be rendered.
Sample code:
Here is an example showing how to render additional text content based on a condition:
import React, { useState } from 'react'; const WarningBanner = ({ warning }) => { if (!warning) { return null; } return <div className="warning">Warning!</div>; }; const Page = () => { const [showWarning, setShowWarning] = useState(false); return ( <div> <h1>Page Title</h1> <WarningBanner warning={showWarning} /> <button onClick={() => setShowWarning(prev => !prev)}> Toggle Warning </button> </div> ); }; export default Page;
In this example, we create aWarningBanner
Component, this component is only inshowWarning
Shown only when true. At the same time, we provide a button to switch the display status of the warning.
Summarize
Conditional rendering is a core feature in React development, which allows us to flexibly display different content based on the state of the application. This article shows several common conditional rendering methods, including:
- use
if
Statement - Use ternary operators
- Use short circuit operator
Through conditional rendering, we can not only improve the user's experience, but also make our components more flexible and maintainable.
In actual development, you can choose the most appropriate conditional rendering method according to your needs, and flexibly use this knowledge to achieve more complex UI interactions.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.