Skip to content

counter

One piece of state, three handlers that borrow it in turn.

The three handlers each take count as &mut, one after another. Nothing is cloned and nothing is 'static: the closures run during the pass that built them, so the borrow checker is satisfied by ordinary scoping.

align="center" justify="center" on the outer <View> is what centres the block; in plain egui, that means measuring the block first and allocating the space around it by hand.

Run it yourself ​

sh
cargo run -p counter
trunk serve --config examples/counter/Trunk.toml

The source is examples/counter/src/lib.rs.

rust
use egui_reactor::prelude::*;
use egui_reactor_elements::prelude::*;

#[component]
pub fn App(cx: &mut Cx) {
    let mut count = use_state(cx, || 0i32);

    rsx! {
        <View direction="column" align="center" justify="center" gap={12} grow={1.0}>
            <Text size={32.0} strong>{format!("{}", *count)}</Text>
            <View direction="row" gap={8}>
                <Button on_click={|| *count -= 1}>"-"</Button>
                <Button on_click={|| *count = 0}>"reset"</Button>
                <Button on_click={|| *count += 1}>"+"</Button>
            </View>
        </View>
    }
}

Released under the MIT or Apache-2.0 license.