Conditional Rendering
Show, Switch, Match, and OptionalWrapper.
Conditional Rendering
This part of Utilinent is for branch logic that deserves to be visible in the JSX. The components here do not invent new rendering semantics. They take patterns you already write with ternaries, &&, and wrapper duplication and make the rule explicit.
Show
Show is the direct replacement for “render this when that is truthy.”
import { Show } from '@ilokesto/utilinent';
function Welcome({ user }: { user: { name: string } | null }) {
return (
<Show when={user} fallback={<p>Please log in</p>}>
{(currentUser) => <h1>Welcome, {currentUser.name}</h1>}
</Show>
);
}Important detail: if when is an array, the shared resolveWhen() helper treats it as “every value must be truthy.”
That means this renders only when both values pass:
<Show when={[isLoggedIn, isAdmin]}>
<button>Admin Console</button>
</Show>Switch and Match
Use Switch when you have several mutually exclusive branches and want the first matching one.
import { Match, Switch } from '@ilokesto/utilinent';
function Status({ status }: { status: 'loading' | 'done' | 'error' }) {
return (
<Switch fallback={<p>Unknown status</p>}>
<Match when={status === 'loading'}><p>Loading...</p></Match>
<Match when={status === 'done'}><p>Done</p></Match>
<Match when={status === 'error'}><p>Failed</p></Match>
</Switch>
);
}Under the hood, Switch flattens fragments and ignores non-Match children. It then returns the first branch whose when value resolves truthy.
OptionalWrapper
OptionalWrapper is for the awkward case where you want to wrap children only when a condition is met.
import { OptionalWrapper } from '@ilokesto/utilinent';
function ProfileLink({ href, children }: { href?: string; children: React.ReactNode }) {
return (
<OptionalWrapper
when={href}
wrapper={(content) => <a href={href}>{content}</a>}
>
{children}
</OptionalWrapper>
);
}It is built on Show, and its optional fallback prop transforms the non-wrapped path.
Tagged variants
Show and Switch are proxy-backed, which is why forms like Show.div and Switch.section are available.
When to choose which primitive
- Use
Showfor one branch plus one fallback. - Use
Switch/Matchfor exclusive branching with several cases. - Use
OptionalWrapperwhen the branch controls whether children get wrapped, not whether they exist.
Next, read Collection Helpers if the problem is repetition rather than branching.