In React, components or elements can be rendered dynamically through JavaScript conditional statements.
Here are several commonly used methods to deal with conditional rendering in React:
1. Use if statement
Use if statements to determine the rendering content in the return value of the render method or function component.
Example
import React from 'react'; import ReactDOM from 'react-dom/client'; class MyComponent extends { render() { const isLoggedIn = ; let content; if (isLoggedIn) { content = <h1>Welcome back!</h1>; } else { content = <h1>Please sign up.</h1>; } return ( <div> {content} </div> ); } } const root = (('root')); (<MyComponent isLoggedIn={true} />);
2. Use ternary operators
In JSX, ternary operators can be used for concise conditional rendering.
Example
import React from 'react'; import ReactDOM from 'react-dom/client'; const MyComponent = (props) => { const isLoggedIn = ; return ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>} </div> ); }; const root = (('root')); (<MyComponent isLoggedIn={true} />);
3. Use the logic and (&&) operator
In JSX, you can use logic and operators for conditional rendering. If the condition is true, the following element is rendered.
Example
import React from 'react'; import ReactDOM from 'react-dom/client'; const MyComponent = (props) => { const isLoggedIn = ; return ( <div> {isLoggedIn && <h1>Welcome back!</h1>} {!isLoggedIn && <h1>Please sign up.</h1>} </div> ); }; const root = (('root')); (<MyComponent isLoggedIn={true} />);
4. Use switch statements
When multiple conditions need to be processed, you can use the switch statement in the render method.
Example
import React from 'react'; import ReactDOM from 'react-dom/client'; class MyComponent extends { render() { const userRole = ; let content; switch (userRole) { case 'admin': content = <h1>Welcome, Admin!</h1>; break; case 'user': content = <h1>Welcome, User!</h1>; break; case 'guest': content = <h1>Welcome, Guest!</h1>; break; default: content = <h1>Who are you?</h1>; } return ( <div> {content} </div> ); } } const root = (('root')); (<MyComponent userRole="admin" />);
summary
-
if
Statement: Suitable inrender
Use the return value of a method or function component to determine the rendering content. - Triple operator: Suitable for concise conditional rendering in JSX.
- Logic and (
&&
) operator: suitable for conditional rendering in JSX, when the condition istrue
Render elements when . -
switch
Statement: Suitable for processing multiple conditions and rendering different contents.
This is the end of this article about React condition judgment. For more related React condition judgment content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!