'How can conditionally render some text in React without using an else branch?
I'm a front-end newbie. I am messing around with some React code in MyFile.tsx. This is what I have:
<p>
{(2 > 1) ? "goodbye world" : "hello world"}
</p>
Happily, this renders "goodbye world". Of course it does.
But I want to use a simple if -- without an else branch. How can I do that?
I tried the following, but it gave me a syntax error:
<p>
{if (2 > 1) ("goodbye world")}
</p>
Solution 1:[1]
From the React Docs:
You may embed expressions in JSX by wrapping them in curly braces. This includes the JavaScript logical
&&operator. It can be handy for conditionally including an element:
{(2 > 1) && ("Goodbye World")}
This is essentially just a ternary operator without the short circuit.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GROVER. |
