pub fn use_virtual_list<'hook, T>(
items: Vec<T>,
item_height: fn(usize) -> f64,
container: NodeRef,
wrapper: NodeRef,
overscan: usize,
) -> impl 'hook + Hook<Output = UseVirtualListHandle<T>>Expand description
A hook that provides virtual scrolling for large lists.
This hook calculates which items should be visible based on the scroll position and container height, improving performance for large lists.
§Example
use yew_hooks::prelude::*;
#[function_component(VirtualList)]
fn virtual_list() -> Html {
let items = (0..10000).collect::<Vec<_>>();
let item_height = |index: usize| 50.0;
let container = use_node_ref();
let wrapper = use_node_ref();
let overscan = 5;
let virtual_list = use_virtual_list(
items,
item_height,
container.clone(),
wrapper.clone(),
overscan,
);
html! {
<>
<div
ref={container}
style="height: 400px; overflow: auto;"
>
<div ref={wrapper}>
{
for virtual_list.visible_items.iter().map(|item| {
html! {
<div
key={item.index}
style={format!(
"position: absolute; top: {}px; height: {}px; width: 100%;",
item.top, item.height
)}
>
{ format!("Item {}", item.data) }
</div>
}
})
}
</div>
</div>
<button onclick={let scroll_to = virtual_list.scroll_to.clone(); Callback::from(move |_| scroll_to(100))}>{"Scroll to 100"}</button>
</>
}
}§Note
When used in function components and hooks, this hook is equivalent to:
/// A hook that provides virtual scrolling for large lists.
///
/// This hook calculates which items should be visible based on the scroll position
/// and container height, improving performance for large lists.
///
/// # Example
///
/// ```rust
/// # use yew::prelude::*;
/// #
/// use yew_hooks::prelude::*;
///
/// #[function_component(VirtualList)]
/// fn virtual_list() -> Html {
/// let items = (0..10000).collect::<Vec<_>>();
/// let item_height = |index: usize| 50.0;
/// let container = use_node_ref();
/// let wrapper = use_node_ref();
/// let overscan = 5;
///
/// let virtual_list = use_virtual_list(
/// items,
/// item_height,
/// container.clone(),
/// wrapper.clone(),
/// overscan,
/// );
///
/// html! {
/// <>
/// <div
/// ref={container}
/// style="height: 400px; overflow: auto;"
/// >
/// <div ref={wrapper}>
/// {
/// for virtual_list.visible_items.iter().map(|item| {
/// html! {
/// <div
/// key={item.index}
/// style={format!(
/// "position: absolute; top: {}px; height: {}px; width: 100%;",
/// item.top, item.height
/// )}
/// >
/// { format!("Item {}", item.data) }
/// </div>
/// }
/// })
/// }
/// </div>
/// </div>
/// <button onclick={let scroll_to = virtual_list.scroll_to.clone(); Callback::from(move |_| scroll_to(100))}>{"Scroll to 100"}</button>
/// </>
/// }
/// }
/// ```
pub fn use_virtual_list<T>(
items: Vec<T>,
item_height: fn(usize) -> f64,
container: NodeRef,
wrapper: NodeRef,
overscan: usize,
) -> UseVirtualListHandle<T>
where
T: Clone + PartialEq + 'static,
{
/* implementation omitted */
}