Home  >  Article  >  Web Front-end  >  Conditional Rendering in React

Conditional Rendering in React

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-09-28 18:21:02117browse

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 <h1>Welcome back!</h1>;
    } else {
        return <h1>Please sign in.</h1>;
    }
}

2. Using Ternary Operators

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

function MyComponent({ isLoggedIn }) {
    return (
        <h1>
            {isLoggedIn ? 'Welcome back!' : 'Please sign in.'}
        </h1>
    );
}

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 (
        <div>
            {isLoggedIn && <h1>Welcome back!</h1>}
            {!isLoggedIn && <h1>Please sign in.</h1>}
        </div>
    );
}

4. Switch Statement

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

function MyComponent({ status }) {
    switch (status) {
        case 'loading':
            return <h1>Loading...</h1>;
        case 'success':
            return <h1>Data loaded successfully!</h1>;
        case 'error':
            return <h1>There was an error!</h1>;
        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 (
        <div>
            <button onClick={() => setIsLoggedIn(!isLoggedIn)}>
                {isLoggedIn ? 'Logout' : 'Login'}
            </button>
            {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
        </div>
    );
}

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!

The above is the detailed content of Conditional Rendering in React. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:useRef Hook ExplainedNext article:useRef Hook Explained