0% found this document useful (0 votes)
209 views2 pages

React Ternary Operator Explained

Uploaded by

Suchi Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
209 views2 pages

React Ternary Operator Explained

Uploaded by

Suchi Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Ternary operator

The ternary operator in React, also known as the conditional operator, is a


concise way to perform conditional rendering or assign values based on a
condition within JSX. It serves as a shorthand for an if...else statement.
Syntax:

Use:
 condition: This is an expression that evaluates to either true or false.
 ?:This is the ternary operator itself, separating the condition from the true
expression.
 expressionIfTrue: This is the value or expression that will be returned or
executed if the condition is true.
 :: This separates the true expression from the false expression.
 expressionIfFalse: This is the value or expression that will be returned or
executed if the condition is false.

Usage in React:

The ternary operator is frequently used in React for:


 Conditional Rendering: Displaying different components or elements based
on a state or prop.
<!DOCTYPE html>

<html>

<body>

<h1 id="demo"></h1>
<script>

function renderApp() {

[Link]("demo").innerHTML = "Welcome!";

function renderLogin() {

[Link]("demo").innerHTML = "Please log in";

let authenticated = true;

authenticated ? renderApp() : renderLogin();

</script>

<p>Try changing the "authenticated" variable to false, and run the code to see what happens.</p>

</body>

</html>

You might also like