DEV Community

TechzPad
TechzPad

Posted on

Conditional Statements in React: If-else, Switch, Break

React is a popular JavaScript library that allows developers to build complex user interfaces quickly and efficiently. One of the most critical aspects of programming in React is the use of conditional statements, which allow developers to control the behavior of their applications based on certain conditions. In this article, we will explore two types of conditional statements that are commonly used in React: if-else statements and switch-break statements.

  1. If-Else Statements in React
    function Greeting(props) {
    const isLoggedIn = props.isLoggedIn;
    if (isLoggedIn) {
    return <h1>Welcome back!</h1>;
    }
    return <h1>Please log in.</h1>;
    }

  2. Switch-Break Statements in React
    function DayOfWeek(props) {
    const day = props.day;
    switch (day) {
    case 0:
    return <h1>Sunday</h1>;
    case 1:
    return <h1>Monday</h1>;
    case 2:
    return <h1>Tuesday</h1>;
    case 3:
    return <h1>Wednesday</h1>;
    case 4:
    return <h1>Thursday</h1>;
    case 5:
    return <h1>Friday</h1>;
    case 6:
    return <h1>Saturday</h1>;
    default:
    return null;
    }
    }

  3. Break Statements in Switch Statements
    function calculateDiscount(level) {
    let discount = 0;
    switch (level) {
    case 'Gold':
    discount = 0.2;
    break;
    case 'Silver':
    discount = 0.1;
    break;
    case 'Bronze':
    discount = 0.05;
    break;
    default:
    break;
    }
    return discount;
    }

Read More Article Click Here

Top comments (0)