zgui

Components

Write reusable pieces of interface with

A component is a Rust function that builds a piece of interface. #[component] makes the function callable from a view, with named arguments that are checked at compile time. To write a component without the macro, see Without macros.

Define a component

use zgui::prelude::*;

/// A labelled value.
#[component]
fn Stat(
    /// What the value is called.
    #[prop(into)]
    label: String,
    /// The value, which follows whatever produced it.
    value: Signal<i32>,
) -> impl IntoView {
    view! {
        row(class = "stat") {
            label(class = "stat__label") {{label}}
            text(class = "stat__value") {{move || value.get().to_string()}}
        }
    }
}

Call it like any node, and write its arguments as attributes:

view! {
    column {
        Stat(label = "Used", value = used.into())
        Stat(label = "Free", value = free.into())
    }
}

A component is a normal Rust item. Put one per file or several in a module. The generated props types take the function's visibility, so pub fn Card is a public component.

Props

Every argument is a prop. The caller writes props by name, in any order.

A prop with no #[prop] attribute is required. Leaving it out is a compile error that names the prop:

error[E0277]: `Thing` is missing the required prop `label`
  --> src/main.rs:21:21
21 |     let _ = view! { Thing(times = 2) };
   |                     ^^^^^ `label` was never given

Optional props and defaults

#[prop(...)] changes how a prop is passed:

Prop

Type

You can combine them: #[prop(into, optional)], #[prop(into, default = 1)], #[prop(into, name = "type")].

/// A labelled value.
#[component]
fn Field(
    /// The label.
    #[prop(into)]
    label: String,
    /// Shown after the label when present.
    #[prop(into, optional)]
    hint: Option<String>,
    /// How many columns the field spans.
    #[prop(default = 1)]
    span: u8,
) -> impl IntoView {
    view! { {label}{hint}{span.to_string()} }
}

// `hint` and `span` may be left out; `label` may not.
view! { Field(label = "Name") }
view! { Field(label = "Address", hint = "optional", span = 2) }

An Option<T> prop takes a T at the call site: write hint = "optional", not hint = Some("optional"). It also accepts an Option<T>, so a wrapper component can pass its own optional prop through unchanged.

Only #[prop(...)] and doc comments are allowed on an argument. Doc comments appear on the generated builder in rustdoc.

What a caller can pass

Declared typeThe caller can pass
Ta T
T with #[prop(into)]anything Into<T>
Option<T>, optionala T or an Option<T>
Childrena children block, built once. See Children and slots
ChildrenFna children block that can be built more than once
ReactiveValue<T> with #[prop(into)]a constant, a signal, a memo or a closure

Like Signal<T>, ReactiveValue<T> lets a component accept anything readable as a T. See Derived state.

When the body runs

A component's body runs once, when the component is built. Stat(...) builds its part of the document and returns. Changing value later does not call Stat again; only the closure that reads value runs again. There is no virtual DOM and no diffing: a component is a constructor, not a render function.

This means a plain prop is a value read once. An i32 prop is the number passed at build time and never changes. To pass something that changes, pass a signal, memo or closure, and read it inside a reactive hole:

#[component]
fn Bad(count: i32) -> impl IntoView {
    // `count` was read once. This text never changes.
    view! { text {{count.to_string()}} }
}

#[component]
fn Good(count: Signal<i32>) -> impl IntoView {
    // Read inside a closure, so it follows the signal.
    view! { text {{move || count.get().to_string()}} }
}

A component written inside a reactive hole (a closure child, or a Dynamic) runs again each time that hole re-runs. Before each run, its scope is cleaned up: the previous run's signals, effects and tasks are disposed of, and the new output updates the existing nodes in place. To keep state across those runs, create it outside the hole.

Scope and cleanup

Each component has its own reactive scope. Signals, contexts, stored values, effects and tasks created in its body belong to it.

When the component is removed, for example because a branch is hidden or a row is deleted, its scope is disposed of synchronously, in the same frame: effects stop, stored values are dropped, tasks are cancelled and cleanup closures run. See Context and Effects and lifecycle.

Forward attributes to an element

A component that wraps an element often lets its caller add classes, listeners or accessibility attributes to that element. #[prop(attrs)] collects them, and a spread applies them:

#[component]
fn Button(
    /// Whatever the caller forwarded.
    #[prop(attrs)]
    attrs: Attrs,
    children: Children,
) -> impl IntoView {
    view! {
        control(class = "button", {..attrs}) {
            {children.into_view_once()}
        }
    }
}
view! {
    Button(class = "button--primary", on:click = save) {"Save"}
}

Attributes before the spread are applied first and attributes after it are applied last, so their position decides which one wins. The bundle carries classes, style: declarations, custom properties, attributes, properties, states, listeners and accessibility values. Attributes has the merge rules.

Several class values merge instead of replacing each other. Each can be a string or an existing Classes list. Duplicates are removed, and each class keeps its first position:

control(class = "button", class = classes_from_caller) {"Save"}

Classes::merged does the same in Rust: base.merged("button--primary").

Signature rules

#[component] rejects a function it cannot turn into a component, with an error that names the rule:

RuleWhy
The name is upper camel case.Lower-case names in a view are elements.
It has a return type, usually -> impl IntoView.A component returns a view.
It is a free function with no self.Props are named arguments.
It has no lifetime parameters.Props must outlive the call that built them.
Each argument is a plain identifier.A prop needs a name, not a pattern.
No argument type is impl Trait.Props are stored in a struct. Use a type parameter instead.

Type and const generics are allowed, including where clauses:

#[component]
fn Twice<F>(
    /// Called once per repetition, with the index.
    children: F,
) -> impl IntoView
where
    F: Fn(usize) -> AnyView + 'static,
{
    view! { {children(0)}{children(1)} }
}

The entry point is the function app(), not a type called App, so you can use App as the name of your root component.

Next

On this page