Skip to main content

Component

Trait Component 

Source
pub trait Component: Sized {
    type Props;
    type State;
    type Msg: Clone + Send + 'static;

    // Required methods
    fn init(props: &Self::Props) -> Self::State;
    fn update(state: &mut Self::State, msg: Self::Msg) -> Cmd<Self::Msg>;
    fn view(
        props: &Self::Props,
        state: &Self::State,
        ctx: &mut ViewCtx<'_, Self::Msg>,
    );
}
Expand description

A reusable UI component with its own state and messages

Components follow a “parent owns state” model (Elm-style). The parent allocates and stores the component’s State, and passes Props when rendering.

§Example

struct Counter;

impl Component for Counter {
    type Props = i32;  // initial value
    type State = i32;  // current count
    type Msg = CounterMsg;

    fn init(props: &Self::Props) -> Self::State {
        *props
    }

    fn update(state: &mut Self::State, msg: Self::Msg) -> Cmd<Self::Msg> {
        match msg {
            CounterMsg::Increment => *state += 1,
            CounterMsg::Decrement => *state -= 1,
        }
        Cmd::none()
    }

    fn view(props: &Self::Props, state: &Self::State, ctx: &mut ViewCtx<Self::Msg>) {
        ctx.horizontal(|ctx| {
            ctx.button("-", CounterMsg::Decrement);
            ctx.ui.label(format!("{}", state));
            ctx.button("+", CounterMsg::Increment);
        });
    }
}

Required Associated Types§

Source

type Props

Props passed from parent (immutable, for display/config)

Source

type State

Internal state (owned by parent, mutated via update)

Source

type Msg: Clone + Send + 'static

Messages for this component

Required Methods§

Source

fn init(props: &Self::Props) -> Self::State

Initialize state from props

Source

fn update(state: &mut Self::State, msg: Self::Msg) -> Cmd<Self::Msg>

Update state based on message

Source

fn view( props: &Self::Props, state: &Self::State, ctx: &mut ViewCtx<'_, Self::Msg>, )

Render the component

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§