Muhammad Hamza f0209c786f
Prepare for Yew 0.20 (#2973)
* 0.20 Changelog

* Improve changelog generator

* Add blog post

* Add blog post

* Apply suggestions from code review

Co-authored-by: WorldSEnder <WorldSEnder@users.noreply.github.com>
Co-authored-by: Julius Lungys <32368314+voidpumpkin@users.noreply.github.com>

* update Changelog

* update Cargo.toml

* changelog gen compiles

* website version 0.20

* add migration guides

* prettier

* i18n

Co-authored-by: WorldSEnder <WorldSEnder@users.noreply.github.com>
Co-authored-by: Julius Lungys <32368314+voidpumpkin@users.noreply.github.com>
2022-11-25 15:19:07 +05:00

75 lines
1.9 KiB
Plaintext

---
title: 'Callbacks'
---
Callbacks are used to asynchronously communicate upwards the components tree and with other things like agents or the DOM during event handling.
Internally their type is just an `Fn` wrapped in `Rc` to allow them to be cheaply cloned.
They have an `emit` function if you want to call them manually.
```rust
use yew::{html, Component, Context, Html, Callback};
let cb: Callback<String, String> = Callback::from(move |name: String| {
format!("Bye {}", name)
});
let result = cb.emit(String::from("Bob")); // call the callback
// web_sys::console::log_1(&result.into()); // if uncommented will print "Bye Bob"
```
## Passing callbacks as props
A common pattern in yew is to create a callback and pass it down as a prop.
```rust
use yew::{function_component, html, Html, Properties, Callback};
#[derive(Properties, PartialEq)]
pub struct Props {
pub on_name_entry: Callback<String>,
}
#[function_component]
fn HelloWorld(props: &Props) -> Html {
props.on_name_entry.emit(String::from("Bob"));
html! { "Hello" }
}
// Then supply the prop
#[function_component]
fn App() -> Html {
let on_name_entry: Callback<String> = Callback::from(move |name: String| {
let greeting = format!("Hey, {}!", name);
// web_sys::console::log_1(&greeting.into()); // if uncommented will print
});
html! { <HelloWorld {on_name_entry} /> }
}
```
## DOM Events and Callbacks
Callbacks are also used to hook into DOM events.
For example here we define a callback that will be called when the user clicks the button:
```rust
use yew::{function_component, html, Html, Properties, Callback};
#[function_component]
fn App() -> Html {
let onclick = Callback::from(move |_| {
let greeting = String::from("Hi there");
// web_sys::console::log_1(&greeting.into()); // if uncommented will print
});
html! {
<button {onclick}>{ "Click" }</button>
}
}
```