To use the the components in React conditionally we can make use of if-else conditions in JavaScript.
In this React rendering example we saw how we can do that. But what if we want a shorter syntax? We can use inline conditions in JSX to do that.
There are two different ways we can use inline if in React.
Inline If with Logical && Operator
Just embed the expressions by wrapping them into curly braces including the JavaScript logical operator (&&).
Just like this:
{unreadMessages.length > 0 &&
You have {unreadMessages.length} unread messages.
}
This is how it works:
- true && expression => expression
- false && expression => false
So, if the condition before && is true then React will go for the code after && and will render the output. If not, React will ignore it and skip the execution of the code after &&.
Here’s the demo:
Inline If-Else with Conditional Operator
You can also use Conditional Operator in JavaScript for inline conditional rendering.
Like this:
condition ? true : false
Just like this example we can just conditionally render one or more words.
It doesn’t have to be just one word. We can use it with a larger expressions as well.
Let’s try to change the elements storing in variables example
components if-else inline syntax