Show
<Show when={condition} fallback={...}>children</Show> renders its children while when is truthy and fallback otherwise.
<Show when={condition} fallback={...}>children</Show> renders its children while when is truthy and fallback otherwise. Falsy is the JavaScript meaning (null, undefined, false, 0, NaN, ""); everything else is truthy, including [] and {}. Note that 0 is falsy: <Show when={items.length}> hides the list when it is empty.
- The children are created when the branch is first shown, not before. Hidden children never run.
- The branch is rebuilt only when the truthiness of
whenflips. Whilewhenstays truthy, the children are kept and updated in place by their own bindings. - When the branch is replaced, its owner is disposed: effects stop,
onCleanupcallbacks run, and the DOM is removed. fallbackis read lazily, only while it is shown. It is not created whenwhenis truthy.- The ternary
{when() ? <A /> : <B />}and the&&form in JSX are compiled with a memoized condition, so they rebuild only when the truthiness changes as well.Showadds the callback forms below and the fallback laziness.
Callback children#
If the child is a function, Show calls it once per built branch, untracked, with an accessor of the latest truthy value. This removes the need for non-null assertions:
import { useStore } from "@shadow-js/core";
import { Show } from "@shadow-js/web";
interface User {
name: string;
}
export function Greeting() {
const [session] = useStore<{ user: User | null }>({ user: { name: "Ada" } });
return <Show when={session.user}>{(current) => <p>Hello {current().name}</p>}</Show>;
}
The accessor follows later values of when while the branch is alive. Reading it after the branch was replaced (the condition became falsy) throws a TypeError whose message starts with ShadowJS Show: stale accessor. A cleanup running as the branch is torn down may still read it and gets the last truthy value.
With keyed, the callback receives the value itself, and the branch is rebuilt whenever the identity of when changes (not only the truthiness):