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