Conditionally render elements:
{props.inStock === 0 && <div className="sold-out">SOLD OUT</div>}
<h1>{ age >= legalAge ? 'Accepted' : 'Denied' }</h1>
Conditionally render different components:
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
You can use conditionals, to "conditionally render" different elements or components.
export default function Card(props) {
let inventory
if (props.inStock === 0) {
inventory = "SOLD OUT"
} else if (props.inStock > 0) {
inventory = `We have ${props.inStock} available`
}
return (
<div className="product-info">{inventory}</div>
)
};
Can use if statements like so.
Conditionally render elements:
<p>{ stock > 0 ? 'In Stock' : 'Not available' }</p>
<p>{ shipped ? 'Item shipped' + '✔' : 'Hasn't been shipped yet... ' + processPhase }</p>
{ checked ? <del>item</del> : <p>Still in place</p> }
Conditionally render different components:
{ isLoggedIn ? <User /> : <Guest /> }
Can be used instead of if statements for inline conditional rendering. { boolean ? true : false }
Conditionally render elements:
{variable && <h1> Welcome! </h1>}
{variable && ✔ }
Conditionally render components:
{variable && <Greeting />}
{variable && <Leaving />}
If left is true, right gets rendered. Use curly braces.
function Comp1(){
return <h1>Hi Component 1 Here!</h1>
}
function Comp2(){
return <h1>Hi Component 2 Here!</h1>
}
function Switch({number}){
return (
<div>
{(() => {
switch (number) {
case 1:
return <Comp1 />
case 2:
return <Comp2 />
default:
return null
}
})()}
</div>
)
}
Some cases you might want to use switch statements.