"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Conditional Rendering in React

Conditional Rendering in React

Published on 2024-11-08
Browse:881

Conditional Rendering in React

Conditional rendering in React allows you to render different components or elements based on certain conditions, such as state or props. Here are some common methods to achieve conditional rendering:

1. Using If-Else Statements

You can use standard JavaScript if-else statements inside your component.

function MyComponent({ isLoggedIn }) {
    if (isLoggedIn) {
        return 

Welcome back!

; } else { return

Please sign in.

; } }

2. Using Ternary Operators

This is a concise way to render content based on a condition.

function MyComponent({ isLoggedIn }) {
    return (
        

{isLoggedIn ? 'Welcome back!' : 'Please sign in.'}

); }

3. Using Logical && Operator

You can use the logical AND operator to render a component only if a condition is true.

function MyComponent({ isLoggedIn }) {
    return (
        
{isLoggedIn &&

Welcome back!

} {!isLoggedIn &&

Please sign in.

}
); }

4. Switch Statement

For more complex conditions, you can use a switch statement.

function MyComponent({ status }) {
    switch (status) {
        case 'loading':
            return 

Loading...

; case 'success': return

Data loaded successfully!

; case 'error': return

There was an error!

; default: return null; } }

Example

Here’s a full example using functional components:

import React from 'react';

function App() {
    const [isLoggedIn, setIsLoggedIn] = React.useState(false);

    return (
        
{isLoggedIn ?

Welcome back!

:

Please sign in.

}
); } export default App;

Summary

Choose the method that best suits your needs based on the complexity of your conditions and your personal coding style. Let me know if you need more examples or explanations!

Release Statement This article is reproduced at: https://dev.to/imyusufakhtar/conditional-rendering-in-react-43h2?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3