Function ForEnumerate

pub fn ForEnumerate<IF, I, T, EF, N, KF, K>(
    props: ForEnumerateProps<IF, I, T, EF, N, KF, K>,
) -> impl IntoView
where IF: Fn() -> I + Send + 'static, I: IntoIterator<Item = T> + Send + 'static, EF: Fn(ReadSignal<usize>, 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.

Compared with For, it has an additional index parameter, which can be used to obtain the current index in real time.

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>
      <ForEnumerate
        // 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 |index: ReadSignal<usize>, counter: Counter| {
          view! {
            <button>{move || index.get()} ". Value: " {move || counter.count.get()}</button>
          }
        }}
      />
    </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 index and the item, and returns the view that will be displayed for each item.