Перейти к содержанию

For

{"<for>"}

The <For> component is used to render a list of items. It is similar to the .map() function in JavaScript.

1
2
3
4
5
function For<T, U extends JSX.Element>(props: {
  each: readonly T[];
  fallback?: JSX.Element;
  children: (item: T, index: () => number) => U;
}): () => U[];

A referentially keyed loop with efficient updating of only changed items. The callback takes the current item as the first argument:

1
2
3
<For each={state.list} fallback={<div>Loading...</div>}>
  {(item) => <div>{item}</div>}
</For>

The each prop can also be a function that returns a list. This is useful for creating a loop that depends on a state value:

1
<For each={stateSignal()}>{(item) => <div>{item}</div>}</For>

The optional second argument is an index signal:

1
2
3
4
5
6
7
<For each={state.list} fallback={<div>Loading...</div>}>
  {(item, index) => (
    <div>
      #{index()} {item}
    </div>
  )}
</For>

Props

Name Type Description
each readonly T[] The list of items to render.
fallback JSX.Element A fallback element to render while the list is loading.
children (item: T, index: () => number) => U A callback that returns a JSX element for each item in the list.

Комментарии