React Fundamentals

0% completed

Previous
Next
Conditional Rendering with Ternaries

Another popular and clean way to conditionally render component is through the use of ternary operators. A ternary operator is a shorthand for an if-else statement.

The ? stands for if and the : stands for else.

Syntax

condition ? expression_if_true : expression_if_false
  • condition: The expression that will be evaluated to either true or false.
  • expression_if_true: The result that will be returned if the condition is true.
  • expression_if_false: The result that will be returned if the condition is false.

The ternary operator can be used within JSX to conditionally render different UI elements based on certain conditions.

Using the user login example in the previous lesson, we can convert the code to conditionally render using ternaries:

function App() { const isUserLoggedIn = true; return ( <div> <h1>React Course</h1> {isUserLoggedIn ? <p>Welcome back!</p> : <p>Please log in</p>} </div> ); }

In this example:

  • The isUserLoggedIn variable is set to true.
  • Inside the JSX, the ternary operator checks whether isUserLoggedIn is true or false.
    • If true, it renders the message "Welcome back!".
Image
  • If false, it renders "Please log in."
Image

Ternary Operator with JSX Components

You can also use ternary operators to conditionally render entire components. For instance, you may want to show different components based on whether a user is an admin or a regular user.

function AdminPanel() { return <div>Admin Panel</div>; } function UserPanel() { return <div>User Panel</div>; } export default function Dashboard({ user }) { return ( <div> {user.isAdmin ? <AdminPanel /> : <UserPanel />} </div> ); }

In this example, the AdminPanel component is rendered if user.isAdmin is true; otherwise, the UserPanel component is rendered, returning their respective JSX.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next