If
Component for conditional rendering with only if logic (no else clause).
Signature
function If<T>(predicate: () => T, renderIf: (value: T) => Node): Node;Parameters
predicate: () => T- Function that returns a value to evaluate as truthy/falsyrenderIf: (value: T) => Node- Function to render when predicate is truthy
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 = If(
isAuthenticated,
(isAuth) => html`<h2>Hi ${user().name}!</h2>`
);Behavior
Renders content only when the predicate is truthy
Renders nothing (empty text node) when the predicate is falsy
Internally uses
IfOrElsewith an empty else clauseProvides the actual predicate value to the render function
Advanced Usage
// Multiple conditions
const [isAuthenticated, setIsAuthenticated] = createSignal(false);
const [user, setUser] = createSignal({
name: "John Doe",
email: "john.doe@pm.me",
});
const template = html`<div>
${If(isAuthenticated, (value) => html`<h2>Hi ${user().name}!</h2>`)}
${If(
() => !isAuthenticated(),
(value) => html`<h2>Welcome 👋</h2>`
)}
<button onclick="${() => setIsAuthenticated(!isAuthenticated())}">
Switch
</button>
</div>`;Best Practices
Use
Ifwhen you only need to show something conditionallyUse
IfOrElsewhen you need to show different content based on a conditionIfis more concise for simple conditional rendering
Last updated