For

Component for rendering lists that automatically updates when the array changes.

Signature

function For<T>(
  items: () => Array<T>,
  renderItem: (item: T, index: number) => Node
): Node;

Parameters

  • items: () => Array<T> - Function that returns an array of items to render

  • renderItem: (item: T, index: number) => Node - Function to render each item

Returns

  • Node - A DOM node containing all rendered items

Example

const [tasks, setTasks] = createSignal([
  { id: "I", text: "Inhale", completed: true },
  { id: "E", text: "Exhale", completed: true },
  { id: "R", text: "Repeat", completed: false },
]);

const template = html`
  <div>
    <h2>Todo List</h2>
    <ul>
      ${For(
        tasks,
        (task, index) => html`
          <li>
            <input
              type="checkbox"
              checked="${task.completed}"
              onchange="${() => console.log("toggleTask", task.id)}"
            />
            <span>${index + 1}. ${task.text}</span>
            <button onclick="${() => console.log("delTask", task.id)}">
              X
            </button>
          </li>
        `
      )}
    </ul>
  </div>
`;

Advanced Usage

Behavior

  • Re-renders the entire list when the array changes

  • Compares arrays using length and Object.is() for each item

  • Automatically cleans up previous renders before creating new ones

  • Provides both item and index to the render function

Performance Notes

  • The For component re-renders the entire list when the array changes

  • For large lists, consider implementing virtual scrolling or pagination

  • Use computed values for filtering/sorting to optimize performance

  • Avoid creating new objects in the render function to prevent unnecessary re-renders

Last updated