forEach
Render a template for each item in an array.
/** * Render a template for each item in an array. * @param array Array or function returning array. * @param arg2 Template function or key string. * @param arg3 Template function if arg2 is a key. * @returns Function to mount the list. */type ForEach<T> = (item: T, index: number) => VNodeValue;
export function forEach<T>( each: T[] | (() => T[]), arg2: ForEach<T> | keyof T, arg3?: ForEach<T>)
Render lists declaratively. Supports reactive arrays via signal. You can provide a template function, and optionally a key for efficient DOM updates.
Basic Usage
Section titled “Basic Usage”import { signal } from '@hellajs/core';import { html, forEach } from '@hellajs/dom';
const { ul, li } = html;
const items = signal([1, 2, 3]);
const List = ul( forEach(items, (item) => li(`Item ${item}`) ));
Static Array
Section titled “Static Array”const StaticList = ul( forEach([10, 20, 30], (item, i) => li(`Static ${item}`) ));
Keys are used for efficient DOM updates. You can set keys in several ways:
Property Name
Section titled “Property Name”Pass a string as the second argument to use a property as the key.
const users = signal([ { index: 1, name: 'Alice' }, { index: 2, name: 'Bob' }]);
const UserList = ul( forEach(users, 'index', (user) => li(user.name) ));
”id” Fallback
Section titled “”id” Fallback”If you do not provide a key, but your items have an id
property, forEach
will use item.id
as the key automatically.
const users = signal([ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]);
const UserList = ul( forEach(users, (user) => li(user.name) ));
Manual
Section titled “Manual”You can also set the key directly on the element.
const users = signal([ { index: 1, name: 'Alice' }, { index: 2, name: 'Bob' }]);
const List = ul( forEach(users, (item) => li({ key: item.index }, `Item ${item.name}`) ));