Conditional Rendering
What is Conditional Rendering?
When using props in components, it is possible to make if else statements change what JSX the tree returns.
If Else Statements
This is probably the most used statement and tells code to return a certain piece of code if something is correct (or incorrect). If that is not the case it will return something else.
The way this is used in React is relatively similar to what it looks like in Vanilla JS, but it does obviously contain some JSX code and a return statement.
function Item({ name, isPacked }) {
if (isPacked) {
return <li className="item">{name} ✔</li>
}
return <li className="item">{name}</li>
}
The situation will probably appear where you sometimes do not want to render anything. You can then also return null
.
if (isPacked) {
return null
}
return <li className="item">{name}</li>
Ternary Operator
Instead of putting the list item in the return statement inside of the conditional statement like in the above part is described, you can also use a ternary operator inside of the 'big' return statement of the component, so inside of the JSX.
return (
<li className="item">
{isPacked ? name + ' ✔' : name}
</li>
)
Logical AND Operator (&&)
The logical AND operator comes up often in JavaScript. You can use this when you want to render some JSX when a condition is true, or render nothing otherwise.
return (<li className="item">{name} {isPacked && '✔️'}</li>);
Just a Tip: There should never be numbers on the left side of &&
, since JavaScript automatically converts the left side in to a boolean. If the left side is 0
, the whole expression gets that value and React will happily render 0
, rather than nothing.
Logical OR Operator ( || )
This operator will only return if one or the other is true. So, this operator will usually work with Boolean values.
const a = 4
const b = -8
console.log(a > 0 || b > 0)
You can do a lot with this operator, because only one has to be true. Do keep in mind that if both things happen to be true, it will only return the first argument that is true.
You can also add more than two expressions, but remember all of the above rules still apply.