Skip to content

Instantly share code, notes, and snippets.

@WorldSEnder
Created April 11, 2022 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WorldSEnder/c659fed693de3da35a421a5a78c3fb0d to your computer and use it in GitHub Desktop.
Save WorldSEnder/c659fed693de3da35a421a5a78c3fb0d to your computer and use it in GitHub Desktop.
Function component Yew counter example
use gloo_console as console;
use js_sys::Date;
use std::rc::Rc;
use yew::{function_component, html, use_reducer, Callback, Html, Reducible};
// Define the possible actions which can be sent to the counter
pub enum Action {
Increment,
Decrement,
}
#[derive(Default, Clone)]
struct Counter {
value: i64,
}
impl Reducible for Counter {
type Action = Action;
fn reduce(mut self: std::rc::Rc<Self>, action: Self::Action) -> std::rc::Rc<Self> {
let state = Rc::make_mut(&mut self);
match action {
Action::Increment => {
state.value += 1;
console::log!("plus one"); // Will output a string to the browser console
}
Action::Decrement => {
state.value -= 1;
console::log!("minus one");
}
}
self
}
}
#[function_component]
fn App() -> Html {
let counter = use_reducer(Counter::default);
let onincrement = {
let counter = counter.dispatcher();
Callback::from(move |_| counter.dispatch(Action::Increment))
};
let ondecrement = {
let counter = counter.dispatcher();
Callback::from(move |_| counter.dispatch(Action::Decrement))
};
let ondoubleincr = {
let counter = counter.dispatcher();
Callback::from(move |_| {
counter.dispatch(Action::Increment);
counter.dispatch(Action::Increment);
})
};
html! {
<div>
<div class="panel">
// A button to send the Increment message
<button class="button" onclick={onincrement}>
{ "+1" }
</button>
// A button to send the Decrement message
<button onclick={ondecrement}>
{ "-1" }
</button>
// A button to send two Increment messages
<button onclick={ondoubleincr}>
{ "+1, +1" }
</button>
</div>
// Display the current value of the counter
<p class="counter">
{ counter.value }
</p>
// Display the current date and time the page was rendered
<p class="footer">
{ "Rendered: " }
{ String::from(Date::new_0().to_string()) }
</p>
</div>
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment