How to Use Ternary Operator in React Js

Hello devs,

In this lesson, I will teach you the use of the Ternary Operator in React for the conditional rendering of JSX and explains it with the help of examples. 

You know that a ternary operator also called Conditional Operator is the 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 js too.

See the below example:


Now we want to use the ternary operator like if you want to use an if-else statement within the returned JSX, you can do it by using a JavaScripts ternary operator:


Another way of doing the same above thing, if you only return one side of the conditional rendering anyway, is using the && operator:


Read also: React Redux Complete Setup Example with Api Call


Hope it can help you.


Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js