10 Conditional Rendering Examples in CSS and React.js πŸš€ (Part 2)

WHAT TO KNOW - Sep 7 - - Dev Community

<!DOCTYPE html>





10 Conditional Rendering Examples in CSS and React.js πŸš€ (Part 2)

<br> body {<br> font-family: sans-serif;<br> }</p> <div class="highlight"><pre class="highlight plaintext"><code> h1, h2, h3 { margin-bottom: 1rem; } code { background-color: #f2f2f2; padding: 0.2rem 0.4rem; border-radius: 3px; } pre { background-color: #f2f2f2; padding: 1rem; border-radius: 3px; overflow-x: auto; } .example-container { border: 1px solid #ddd; padding: 1rem; margin-bottom: 1rem; } </code></pre></div> <p>



10 Conditional Rendering Examples in CSS and React.js πŸš€ (Part 2)



Welcome back to the second part of our deep dive into conditional rendering in CSS and React.js! In the previous article, we laid the groundwork with foundational concepts and simple examples. Now, we'll explore more advanced techniques and showcase their real-world applications.



CSS Conditional Rendering



CSS, being a declarative language, doesn't directly offer conditional statements like "if" or "else." Instead, we leverage CSS preprocessors like Sass or Less to implement conditional logic.


  1. Using Media Queries for Responsive Design

Media queries are a powerful tool to adapt your website's layout and styling to different screen sizes and orientations. This is a classic example of conditional rendering in CSS.


@media (max-width: 768px) {
.container {
display: flex;
flex-direction: column;
}
}

This code snippet defines styles for the ".container" class specifically when the screen width is less than 768px. It changes the layout to a vertical column for smaller screens, improving the user experience.

  • Conditional Styling Based on User Interactions

    Using CSS pseudo-classes, we can target elements based on their state, such as being hovered over or focused. This enables conditional styling based on user interactions.

    
    .button {
    background-color: #4CAF50;
    color: white;
    }
  • .button:hover {
    background-color: #3e8e41;
    }

    .button:focus {
    outline: 2px solid #000;
    }



    The above code defines a green button. When hovered, the background color darkens slightly. When focused, the button gets a black outline.



    React.js Conditional Rendering



    React.js, being a component-based library, offers flexibility in conditionally rendering different parts of your UI based on data and user actions.


    1. Ternary Operator for Basic Conditions

    The ternary operator provides a concise way to render different elements based on a condition.

    
    import React, { useState } from 'react';
    
    
    

    function Counter() {
    const [count, setCount] = useState(0);

    return (


    Count: {count}


    setCount(count + 1)}>
    {count > 5 ? 'Stop Counting' : 'Increment'}


    );
    }

    export default Counter;




    This component displays a counter. The button text changes to "Stop Counting" when the count exceeds 5, demonstrating conditional rendering using the ternary operator.


    1. Logical AND Operator (&&) for Short-Circuit Evaluation

    The logical AND operator allows you to render elements only if a condition is true.

    
    import React, { useState } from 'react';
    
    
    

    function TodoList() {
    const [todos, setTodos] = useState([]);
    const [newTodo, setNewTodo] = useState('');

    const addTodo = () => {
    setTodos([...todos, newTodo]);
    setNewTodo('');
    };

    return (


    setNewTodo(e.target.value)} />
    Add Todo
      {todos.length > 0 && (
    • You have some todos!
    • )} {todos.map((todo, index) => (
    • {todo}
    • ))}


    );
    }

    export default TodoList;




    This example displays a list of todos. The message "You have some todos!" is rendered only when the list is not empty, using the logical AND operator.


    1. Conditional Rendering with "if" Statements

    For more complex logic, "if" statements provide a clear way to handle multiple conditions.

    
    import React, { useState } from 'react';
    
    
    

    function UserProfile() {
    const [user, setUser] = useState({
    name: 'John Doe',
    isPremium: false,
    });

    return (


    User Profile


    {user.isPremium ? (

    Welcome, Premium Member! You have access to exclusive features.


    ) : (

    Become a premium member for enhanced features.


    )}

    );
    }

    export default UserProfile;




    This component shows a user profile. The displayed message depends on whether the user is a premium member, demonstrated by conditional rendering with an "if" statement.


    1. Using the "switch" Statement for Multiple Conditions

    The "switch" statement offers a structured approach when dealing with multiple conditions.

    
    import React, { useState } from 'react';
    
    
    

    function UserStatus() {
    const [status, setStatus] = useState('offline');

    return (


    User Status



    {
    switch (status) {
    case 'online':
    return '🟒 Online';
    case 'away':
    return '🟑 Away';
    case 'offline':
    return 'πŸ”΄ Offline';
    default:
    return '❓ Unknown';
    }
    }


    );
    }

    export default UserStatus;




    This component displays a user's status (online, away, offline) using the "switch" statement for different possible conditions.


    1. Handling Loading States with Conditional Rendering

    When dealing with asynchronous operations like fetching data, it's crucial to display loading indicators or messages while waiting for the data.

    
    import React, { useState, useEffect } from 'react';
    
    
    

    function FetchData() {
    const [data, setData] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
    const fetchData = async () => {
    try {
    const response = await fetch('https://api.example.com/data');
    const json = await response.json();
    setData(json);
    } catch (error) {
    setError(error);
    } finally {
    setIsLoading(false);
    }
    };

    fetchData();
    

    }, []);

    if (isLoading) {
    return

    Loading...;
    }

    if (error) {
    return

    Error: {error.message};
    }

    if (data) {
    return (


    Data


      {data.map((item, index) => (
    • {item.name}
    • ))}


    );
    }
    }

    export default FetchData;




    This component fetches data from an API. It conditionally displays a loading message, an error message, or the fetched data, demonstrating best practices for handling loading states.


    1. Conditional Rendering with Form Validation

    Conditional rendering is often used to display validation messages or errors in forms.

    
    import React, { useState } from 'react';
    
    
    

    function LoginForm() {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [errors, setErrors] = useState({});

    const handleSubmit = (event) => {
    event.preventDefault();

    const newErrors = {};
    if (email === '') {
      newErrors.email = 'Email is required';
    }
    if (password === '') {
      newErrors.password = 'Password is required';
    }
    setErrors(newErrors);
    
    if (Object.keys(newErrors).length === 0) {
      // Submit the form
      console.log('Form submitted successfully!');
    }
    

    };

    return (



    Email:
    setEmail(e.target.value)}
    />
    {errors.email &&

    {errors.email}

    }


    Password:
    setPassword(e.target.value)}
    />
    {errors.password &&

    {errors.password}

    }

    Login

    );
    }

    export default LoginForm;




    This example demonstrates a simple login form with validation. Error messages are displayed only when there are errors, showcasing the use of conditional rendering for form validation.


    1. Dynamic Component Rendering

    React allows you to render different components based on conditions.



    import React, { useState } from 'react';

    function UserTypeDisplay() {
    const [userType, setUserType] = useState('free');

    return (


    User Type


    {
    userType === 'free' ? (

    ) : userType === 'premium' ? (

    ) : (

    )
    }

    );
    }

    function FreeUser() {
    return

    You are a free user.

    ;
    }

    function PremiumUser() {
    return

    You are a premium user.

    ;
    }

    function UnknownUser() {
    return

    User type is unknown.

    ;
    }

    export default UserTypeDisplay;




    This component renders different components depending on the user's type, showcasing how to dynamically render components based on conditions.


    1. Conditional Routing with React Router

    When building complex applications, you might need to conditionally redirect users to different routes based on authentication, user roles, or other conditions.



    import React from 'react';
    import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';

    function App() {
    const isLoggedIn = false; // Replace with your authentication logic

    return (


    : }
    />
    } />
    : } />


    );
    }

    function HomePage() {
    return

    Welcome to the Home Page!

    ;

    }

    function LoginPage() {
    return

    Login Page

    ;

    }

    function UserProfile() {
    return

    User Profile

    ;

    }

    export default App;







    This example demonstrates conditional routing with React Router. The "HomePage" and "UserProfile" routes are only accessible to logged-in users, while the "LoginPage" is accessible to everyone. The "Navigate" component handles the redirection based on the "isLoggedIn" condition.






    Conclusion





    Conditional rendering is a powerful technique for building dynamic and interactive user interfaces. By understanding the concepts and examples presented in this article, you can enhance the user experience of your applications. Remember to choose the most appropriate approach based on the complexity of your logic and maintain code readability for future maintainability.





    Keep in mind that these are just a few examples, and there are countless ways to implement conditional rendering in CSS and React.js. Explore the possibilities, experiment with different techniques, and create engaging and dynamic user experiences.




    . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
    Terabox Video Player