React JS Ternary Operator Tutorial 🎯

beginner
8 min

React JS Ternary Operator Tutorial 🎯

Welcome to our comprehensive guide on the Ternary Operator in React JS! In this lesson, we'll explore the ternary operator, understand why it's useful, and learn how to use it effectively in your React projects.

What is a Ternary Operator? 📝

A Ternary Operator, also known as a Conditional Operator, is a shorthand way to write an if-else statement in a single line. It takes three operands and has the following structure:

javascript
condition ? expressionIfTrue : expressionIfFalse;

Why Use a Ternary Operator in React? 💡

The ternary operator can help simplify your code, making it more concise and easier to read. It's particularly useful in React when you need to set a state or update a variable based on a condition.

Using the Ternary Operator in React 🎯

Let's dive into a practical example. Suppose we have a user object, and we want to display either the user's name or the message "Guest" based on whether the user is logged in or not.

javascript
const user = { isLoggedIn: true, name: "John Doe" }; function App() { return ( <div> {user.isLoggedIn ? user.name : "Guest"} </div> ); }

In the example above, we're using the ternary operator to check if user.isLoggedIn is true. If it is, we display the user's name; otherwise, we display the message "Guest".

Advanced Example 💡

Now, let's consider a more complex example where we want to display the user's name if they're logged in, but show a login button if they're not.

javascript
const [user, setUser] = useState({ isLoggedIn: false, name: null }); function App() { const handleLogin = () => { setUser({ ...user, isLoggedIn: true, name: "John Doe" }); }; return ( <div> {user.isLoggedIn ? ( <div> Welcome, {user.name} <button onClick={() => setUser({ ...user, isLoggedIn: false })}> Logout </button> </div> ) : ( <button onClick={handleLogin}>Login</button> )} </div> ); }

In this example, we're using the ternary operator to conditionally render either the welcome message with a logout button (if the user is logged in) or the login button (if the user is not logged in).

Quiz 💡

Quick Quiz
Question 1 of 1

What does the Ternary Operator do in React JS?