Ternary Operator in React

This lesson teaches the use of Ternary Operator in React for conditional rendering of JSX and explains it with the help of examples.

A ternary operator — also called Conditional Operator — is the only JavaScript operator which takes three operands and returns a value based on some condition. It’s an alternative for if statement. This could be used for multiple purposes and comes in very handy in React too!

Displaying JavaScript strings, objects, and arrays in React is not enough. What about an if-else statement for enabling conditional rendering? You cannot use an if-else statement directly in JSX, but you can return early from the rendering function. Returning null is valid in React when displaying nothing. Just like we did in the example given below.

Did you know? Conditional rendering in React uses JavaScript operators like if or the conditional operator to create elements representing the current state, and let React show or hide a certain UI element based on a condition.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy