yew_hooks/hooks/
use_title.rs

1use yew::prelude::*;
2
3use super::use_unmount;
4
5/// A side-effect hook that sets title of the page and restore previous title when unmount.
6///
7/// # Example
8///
9/// ```rust
10/// # use yew::prelude::*;
11/// #
12/// use yew_hooks::prelude::*;
13///
14/// #[function_component(Title)]
15/// fn title() -> Html {
16///     use_title("This is an awesome title".to_string());
17///     
18///     html! {
19///         <>
20///         </>
21///     }
22/// }
23/// ```
24#[hook]
25pub fn use_title(title: String) {
26    let pre_title = use_memo((), |_| gloo::utils::document().title());
27
28    if gloo::utils::document().title() != title {
29        gloo::utils::document().set_title(&title);
30    }
31
32    use_unmount(move || {
33        gloo::utils::document().set_title(&pre_title);
34    });
35}