Skip to content
FerroUI/ docs

Search guides, controls, Rust APIs, and XAML.

    Lists, async data, errors, and routing

    An application larger than a form needs lists that keep their items, data that arrives later, parts of the window that can fail without ending the application, and navigation between views. ferroui-view covers each with an element or a hook. The examples are taken from the TodoMVC, ViewInterop, and ReactiveDemoComponents samples.

    In a component that runs again, write the list with for in rsx! and give each item a stable key:

    use ferroui_view::prelude::*;
    #[derive(Clone, PartialEq)]
    pub struct Todo {
    pub id: u32,
    pub title: String,
    }
    #[component(rerender)]
    fn TodoList(todos: Signal<Vec<Todo>>) -> Element {
    let visible = todos.get();
    rsx! {
    StackPanel { spacing: 2.0,
    for todo in visible {
    TextBlock { key: todo.id, text: todo.title }
    }
    }
    }
    }

    When an item moves, the reconciler moves its control instead of making a new one, so focus and state stay with the record. An array index is unsuitable as a key when positions can change.

    In a view that runs once, for_each(each, key, view) follows a signal by itself: an item whose key and value stay keeps its control, a new or changed item gets a new one, and the controls of items that left are removed.

    use ferroui_view::prelude::*;
    fn todo_list(todos: Signal<Vec<Todo>>) -> Element {
    stack_panel()
    .child(for_each(move || todos.get(), |todo: &Todo| todo.id, |todo: Todo| text_block().text(todo.title)))
    .into()
    }

    An items control with virtualization creates its item containers itself. Give it a data template whose items are components, and keep the items and the template in hooks so that later runs do not replace them:

    use ferroui_base::BoxedValue;
    use ferroui_controls::ItemsSource;
    use ferroui_view::prelude::*;
    use std::rc::Rc;
    #[derive(Clone, PartialEq)]
    pub struct Person {
    pub name: String,
    pub city: String,
    }
    #[component(rerender)]
    fn Directory(people: Rc<Vec<Person>>) -> Element {
    let source = use_hook({
    let people = people.clone();
    move || ItemsSource::from_items(people.iter().map(|person| Some(Rc::new(person.clone()) as BoxedValue)))
    });
    let item_template = use_hook(|| template(|person: Person| rsx! {
    StackPanel {
    TextBlock { text: person.name }
    TextBlock { text: person.city }
    }
    }));
    rsx! { ListBox { items_source: source, item_template: item_template } }
    }

    Only the visible items have controls. When a container scrolls out of view, its component is recycled for the next item and patched by the reconciler instead of being mounted anew: in the framework’s test of 10,000 items in a 300-pixel list, scrolling to three distant positions mounted one more component in all. Give the list a bounded height, as for any virtualized list.

    use_future(deps, make) runs a future on the UI thread’s dispatcher when the component first runs, and again whenever deps differ from the previous run. It returns a Signal<AsyncState<T>>: Pending, Ready(T), or Failed(String). suspense shows an element for each state.

    #[component(rerender)]
    fn Search() -> Element {
    let query = use_signal(String::new);
    let results = use_future(query.get(), |query| {
    let query = query.clone();
    async move {
    sleep(Duration::from_millis(300)).await;
    search(&query).await
    }
    });
    rsx! {
    StackPanel {
    TextBox { text: query.two_way() }
    {suspense(
    results,
    || rsx! { TextBlock { text: "Searching..." } },
    |found| rsx! { TextBlock { text: format!("{} crates", found.len()) } },
    |error| rsx! { TextBlock { text: error } },
    )}
    }
    }
    }

    Here search is the application’s own async fn returning Result<Vec<_>, String>. With new dependencies the state goes back to Pending and another future starts. A future whose dependencies were replaced, or whose component was removed, is dropped at once and never writes the state, also when what it awaited had already completed. In this search, each keystroke abandons the previous future during its sleep, so the search runs once typing pauses for 300 ms. The future runs on the UI thread, so what it reads and writes needs no synchronization; blocking work still belongs on a worker (async work).

    error_boundary(
    || rsx! { Report {} },
    |info| rsx! {
    StackPanel {
    TextBlock { text: format!("The report failed: {}", info.message()) }
    Button { on_click: move |_| info.reset(), "Try again" }
    }
    },
    )

    When a run of a component below the boundary panics, on its first run or a later one, the boundary shows its fallback and the rest of the window continues. info.reset() mounts the child again with fresh hooks. The nearest boundary catches; a panic in a fallback goes to the boundary above. Boundaries guard the functions of components, not handlers, effects, or the mounting of controls, and the process’s panic hook still prints the message.

    router(initial, routes) shows the view of the first route whose pattern matches the current path and provides a Router handle to the components below:

    router("/", vec![
    route("/", |_| rsx! { Home {} }),
    route("/people/:id", |m| rsx! { Person { id: m.param("id").unwrap_or_default().to_string() } }),
    route("*", |m| rsx! { NotFound { path: m.path().to_string() } }),
    ])

    :name matches one segment and binds it, * matches the rest of the path, and a last route("*", ..) shows what no other route matches. A component calls use_router() while it runs and keeps the handle, which is Copy, for its handlers: navigate(path), navigate_back(), navigate_and_reset(path), and the reactive current(), can_go_back(), and stack(). The entries of the stack are paths, so state that outlives navigation lives above the router in signals or context. TodoMVC uses its filters (/, /active, /completed) as routes; ReactiveDemoComponents opens a crate’s details as /crate/:name inside an error boundary.

    The router is in-application navigation. In the browser, map routes to the page URL explicitly if users need bookmarks; see navigation.

    Terminal window
    cargo run -p todo-mvc
    cargo run -p reactive-demo-components --no-default-features
    cargo run -p view-interop

    TodoMVC is the TodoMVC specification as components with hooks and a router. ReactiveDemoComponents is a crate browser whose throttled search is a use_future; without default features it searches an in-memory catalogue instead of crates.io. Both have scenario tests: cargo test -p todo-mvc and cargo test -p reactive-demo-components.