IfOrElse
Component for conditional rendering with if/else logic that automatically updates when the condition changes.
Signature
function IfOrElse<T>(
predicate: () => T,
renderIf: (value: T) => Node,
renderElse: () => Node
): Node;
Parameters
predicate: () => T
- Function that returns a value to evaluate as truthy/falsyrenderIf: (value: T) => Node
- Function to render when predicate is truthyrenderElse: () => Node
- Function to render when predicate is falsy
Returns
Node
- A DOM node containing the conditional content
Example
const [isAuthenticated, setIsAuthenticated] = createSignal(false);
const [user, setUser] = createSignal({
name: "John Doe",
email: "john.doe@pm.me",
});
const template = IfOrElse(
isAuthenticated,
(isAuth) => html`
<div>
<h2>Hi ${user().name}!</h2>
<button onclick="${() => setIsConnected(false)}">Logout</button>
</div>
`,
() => html`
<div>
<h2>Welcome 👋</h2>
<button onclick="${() => setIsConnected(true)}">Login</button>
</div>
`
);
Advanced Usage
// Working with loading states
const [loading, setLoading] = createSignal<"idle" | "loading" | "error">(
"idle"
);
const template = IfOrElse(
() => loading() === "loading",
(isLoading) => html`<div class="loading">Loading...</div>`,
() =>
IfOrElse(
() => loading() === "error",
(isError) => html`<div class="error">Something Went Wrong!</div>`,
() => html`<div class="idle">Lorem ipsum dolor sit amet...</div>`
)
);
Behavior
Evaluates the predicate using
Boolean(value)
to determine truthinessOnly re-renders when the truthiness of the predicate changes
Provides the actual predicate value to the
renderIf
functionUses comment markers to track DOM insertion points
Automatically cleans up previous renders when switching conditions
Performance Notes
Minimal DOM manipulation - Only updates when condition changes
Efficient cleanup of previous renders
No unnecessary re-evaluation of render functions
Last updated