0
0
Reactframework~5 mins

Ternary operator usage in React

Choose your learning style9 modes available
Introduction

The ternary operator helps you choose between two things quickly in your React code. It keeps your code short and easy to read.

Showing a message only if a user is logged in, otherwise show a login button.
Changing the color of a button based on whether it is active or not.
Displaying different text depending on a condition, like 'Open' or 'Closed'.
Switching between two images depending on a theme (light or dark).
Syntax
React
condition ? expressionIfTrue : expressionIfFalse
The condition is checked first. If it is true, the code after ? runs.
If the condition is false, the code after : runs instead.
Examples
This sets message to 'Welcome back!' if isLoggedIn is true, otherwise to 'Please log in.'
React
const message = isLoggedIn ? 'Welcome back!' : 'Please log in.';
The button text color is green if isActive is true, otherwise gray.
React
<button style={{ color: isActive ? 'green' : 'gray' }}>Click me</button>
Shows 'Pass' if score is 60 or more, else 'Fail'.
React
const status = score >= 60 ? 'Pass' : 'Fail';
Sample Program

This React component shows a message and a button. The message and button text change based on whether the user is logged in. Clicking the button toggles the login state.

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

export default function LoginMessage() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  return (
    <div>
      <p>{isLoggedIn ? 'Welcome back!' : 'Please log in.'}</p>
      <button onClick={() => setIsLoggedIn(!isLoggedIn)}>
        {isLoggedIn ? 'Logout' : 'Login'}
      </button>
    </div>
  );
}
OutputSuccess
Important Notes

You can use ternary operators inside JSX to decide what to show.

For simple true/false rendering, you can also use condition && expression but ternary is best when you have two choices.

Summary

The ternary operator is a quick way to choose between two values.

It keeps your React code clean and easy to read.

Use it inside JSX to show different things based on conditions.