yew_hooks/hooks/
use_window_size.rs

1use gloo::utils::window;
2use yew::prelude::*;
3
4use super::{use_event_with_window, use_mount, use_raf_state};
5
6/// A sensor hook that tracks dimensions of the browser window.
7///
8/// # Example
9///
10/// ```rust
11/// # use yew::prelude::*;
12/// #
13/// use yew_hooks::prelude::*;
14///
15/// #[function_component(UseWindowSize)]
16/// fn window_size() -> Html {
17///     let state = use_window_size();
18///     
19///     html! {
20///         <>
21///             <b>{ " Width: " }</b>
22///             { state.0 }
23///             <b>{ " Height: " }</b>
24///             { state.1 }
25///         </>
26///     }
27/// }
28/// ```
29#[hook]
30pub fn use_window_size() -> (f64, f64) {
31    let state = use_raf_state(|| {
32        (
33            window().inner_width().unwrap().as_f64().unwrap(),
34            window().inner_height().unwrap().as_f64().unwrap(),
35        )
36    });
37
38    {
39        let state = state.clone();
40        use_event_with_window("resize", move |_: Event| {
41            state.set((
42                window().inner_width().unwrap().as_f64().unwrap(),
43                window().inner_height().unwrap().as_f64().unwrap(),
44            ));
45        });
46    }
47
48    {
49        let state = state.clone();
50        use_mount(move || {
51            state.set((
52                window().inner_width().unwrap().as_f64().unwrap(),
53                window().inner_height().unwrap().as_f64().unwrap(),
54            ));
55        });
56    }
57
58    *state
59}