🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Expert Masterclasses.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEreact

react Documentation

LOADING ENGINE...

React Conditional Rendering with Ternary Operator

Master React components, hooks, and best practices.

Conditional Rendering with Ternary Operator

Author

Pascual Vila

Frontend Instructor.

A more concise way to perform conditional rendering is by using the ternary operator. This operator allows you to evaluate a condition on a single line, which is useful for smaller, more readable components.

Example with ternary operator:

          {`import React, { useState } from "react";

          function ConditionalTernary() {
            const [isLoggedIn, setIsLoggedIn] = useState(false);

            return (
              <div>
                {isLoggedIn ? (
                  <div>
                    <h1>Welcome</h1>
                    <button onClick={() => setIsLoggedIn(false)}>Log out</button>
                  </div>
                ) : (
                  <div>
                    <h1>Please log in</h1>
                    <button onClick={() => setIsLoggedIn(true)}>Log in</button>
                  </div>
                )}
              </div>
            );
          }

          export default ConditionalTernary;`}