Created
April 11, 2022 11:42
-
-
Save WorldSEnder/c659fed693de3da35a421a5a78c3fb0d to your computer and use it in GitHub Desktop.
Function component Yew counter example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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