Skip to content

Conditional rendering

{condition && <element />} includes the element when the condition holds and nothing when it does not:

src/wares.ts2
{(ware.restock ?? 0) > 0 && (
<text x={44} y={25} w={116} h={12} text={`restocks ${ware.restock}`}
font={Fonts.SMALL} valign="middle" shadow color={Colors.DIM} />
)}

{condition ? <a /> : <b />} picks one of two. Either arm may be null:

src/equipment.ts2
{item !== -1
? (
<sprite x={2} y={2} w={36} h={32} item={item} itemCount={-1}
outline={1} shadowColor={0x333333}
options={['Remove', '', '', '', '', '', '', '', '', 'Examine']} />
)
: (
<sprite x="center" y="center" w={32} h={32} sprite={SlotIcons.get(slot) ?? -1} />
)}

-1 is what a container holds in an empty slot.

When the branches differ only in a value, put the choice in the prop:

src/wares.ts2
<text x="right" y={0} w={66} h={16} text={`${ware.price} gp`}
font={Fonts.PLAIN} align="right" valign="middle" shadow
color={ware.price <= coins ? Colors.AMBER : Colors.RED} />

A component can return null before it reaches its markup:

src/wares.ts2
const Special = ({ i }: { i: Int }): Component => {
const ware = WARES.at(i);
if (ware === null) {
return null;
}

A condition is a comparison, and ! works on a Boolean:

{stock > 0 && <BuyButton />} // yes
{stock && <BuyButton />} // no: stock is a number
{!isMember && <Upsell />} // yes, if isMember is a Boolean

A comparison can be named, returned from a helper, or passed as a prop: unlocked={prayer.level <= level}.

hide keeps the element but does not draw it. A conditional leaves it out:

<text hide={bare} text={nameOf(shown)} … /> // nameOf runs whether or not bare
{!bare && <text text={nameOf(shown)} … />} // nameOf runs only when it should