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>