Conditional rendering
Choose a branch at runtime
Section titled “Choose a branch at runtime”An ordinary if in a component runs during setup. For a condition that changes later, use when(condition, yes, no?). The condition can be a boolean, a signal, or a function that reads signals.
const ready = signal(false);mount(root, () => when( ready, () => p("Ready"), () => p("Waiting"), ),);The active factory runs once for the current boolean result. A change from true to false or false to true creates the next branch and disposes the previous one. While the result stays the same, the current DOM and its local state are preserved. Use nested when calls for more branches.
Loading the example…
View source
import { mount, onCleanup, onMount, signal, when } from "min-reactive-framework";import type { Dispose } from "min-reactive-framework";import { button, div, output, p } from "min-reactive-framework/html";import type { DemoLanguage } from "../example-language.js";
export function run(target: HTMLElement, lang: DemoLanguage): Dispose { const ru = lang === "ru"; const open = signal(false); const mounted = signal(0); const unmounted = signal(0);
return mount(target, () => div( { class: "mr-demo-stack" }, button( { type: "button", "aria-expanded": open, on: { click: () => { open.value = !open.value; }, }, }, () => open.value ? ru ? "Закрыть ветку" : "Close branch" : ru ? "Открыть ветку" : "Open branch", ), when( open, () => { onMount(() => { mounted.value++; }); onCleanup(() => { unmounted.value++; }); return p({ class: "mr-demo-panel" }, ru ? "Ветка открыта." : "Branch is open."); }, () => p(ru ? "Ветка закрыта." : "Branch is closed."), ), p(ru ? "Подключений " : "Mounts ", output({ id: "mount-count" }, mounted)), p(ru ? "Очисток " : "Cleanups ", output({ id: "cleanup-count" }, unmounted)), ), );}Preserve a hidden region
Section titled “Preserve a hidden region”Use a reactive hidden attribute when a panel should keep its state while hidden. For example, a draft in an uncontrolled input survives when the DOM node remains mounted.
const open = signal(true);mount(root, () => section({ hidden: () => !open.value }, input({ defaultValue: "Draft" })));Use onCleanup inside a branch factory to release a timer, observer, or pending request when that branch is disposed. See async work for a cancellable request.