Function For

pub fn For<IF, I, T, EF, N, KF, K>(
    props: ForProps<IF, I, T, EF, N, KF, K>,
) -> impl IntoView
where IF: Fn() -> I + Send + 'static, I: IntoIterator<Item = T> + Send + 'static, EF: Fn(T) -> N + Send + Clone + 'static, N: IntoView + 'static, KF: Fn(&T) -> K + Send + Clone + 'static, K: Eq + Hash + SerializableKey + 'static, T: Send + 'static,
Expand description

Iterates over children and displays them, keyed by the key function given.

This is much more efficient than naively iterating over nodes with .iter().map(|n| view! { ... })..., as it avoids re-creating DOM nodes that are not being changed.


#[derive(Copy, Clone, Debug, PartialEq, Eq)]
struct Counter {
  id: usize,
  count: RwSignal<i32>
}

#[component]
fn Counters() -> impl IntoView {
  let (counters, set_counters) = create_signal::<Vec<Counter>>(vec![]);

  view! {
    <div>
      <For
        // a function that returns the items we're iterating over; a signal is fine
        each=move || counters.get()
        // a unique key for each item
        key=|counter| counter.id
        // renders each item to a view
        children=move |counter: Counter| {
          view! {
            <button>"Value: " {move || counter.count.get()}</button>
          }
        }
      />
    </div>
  }
}

For convenience, you can also choose to write template code directly in the <For> component, using the let syntax:


  view! {
    <div>
        <For
          each=move || counters.get()
          key=|counter| counter.id
          let(counter)
        >
            <button>"Value: " {move || counter.count.get()}</button>
        </For>
    </div>
  }

The let syntax also supports destructuring the pattern of your data. let((one, two)) in the case of tuples, and let(Struct { field_one, field_two }) in the case of structs.


  view! {
    <div>
        <For
          each=move || counters.get()
          key=|counter| counter.id
          let(Counter { id, count })
        >
            <button>"Value: " {move || count.get()}</button>
        </For>
    </div>
  }

§Required Props

  • each: [IF]
    • Items over which the component should iterate.
  • key: [KF]
    • A key function that will be applied to each item.
  • children: [EF]
    • A function that takes the item, and returns the view that will be displayed for each item.