-
Notifications
You must be signed in to change notification settings - Fork 5
/
WindowSize.ml
37 lines (30 loc) · 1.14 KB
/
WindowSize.ml
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
module R = Reaml
module WindowSize = struct
type t = {
width : float;
height : float;
}
external innerWidth : float = "innerWidth" [@@bs.val] [@@bs.scope "window"]
external innerHeight : float = "innerHeight" [@@bs.val] [@@bs.scope "window"]
external addEventListener : string -> (unit -> unit) -> unit = "addEventListener"
[@@bs.val] [@@bs.scope "window"]
external removeEventListener : string -> (unit -> unit) -> unit = "removeEventListener"
[@@bs.val] [@@bs.scope "window"]
let[@reaml.hook] use () =
let[@reaml] size, setSize = R.useState { width = innerWidth; height = innerHeight } in
let[@reaml] () =
R.useEffect
(fun () ->
let handler () = setSize { width = innerWidth; height = innerHeight } in
addEventListener "resize" handler;
Some (fun () -> removeEventListener "resize" handler))
None
in
size
end
module Demo = struct
let[@reaml.component "Demo"] make () =
let[@reaml] windowSize = WindowSize.use () in
R.div [] [ R.float windowSize.width; R.string {j|×|j}; R.float windowSize.height ]
end
let () = Demo.make () |> R.renderTo "main"