Skip to content

Commit

Permalink
dom: add create_portal
Browse files Browse the repository at this point in the history
  • Loading branch information
glennsl committed Mar 15, 2022
1 parent 82d0838 commit 41ab37c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/dom.mli
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ val render_to_element : id:string -> Core.element -> unit
^ " found in the HTML."))
| Some element -> render react_element element]

val create_portal : Core.element -> dom_element -> Core.element
[@@js.custom
val create_portal_internal :
Imports.react_dom -> Core.element -> dom_element -> Core.element
[@@js.call "createPortal"]

let create_portal element dom_element =
create_portal_internal Imports.react_dom element dom_element]

type dom_ref = private Ojs.t

module Ref : sig
Expand Down
30 changes: 30 additions & 0 deletions test/test_ml.ml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,21 @@ let withContainer f =
Dom.removeChild doc##.body container;
result

let withContainers2 f =
let container1 = Html.createDiv doc in
Dom.appendChild doc##.body container1;
let container2 = Html.createDiv doc in
Dom.appendChild doc##.body container2;

let result = f container1 container2 in

ignore (React.Dom.unmount_component_at_node container1);
Dom.removeChild doc##.body container1;
ignore (React.Dom.unmount_component_at_node container2);
Dom.removeChild doc##.body container2;

result

let testDom () =
doc##.title := Js.string "Testing";
let p = Html.createP doc in
Expand All @@ -43,6 +58,20 @@ let testReact () =
(Html.element c));
assert_equal c##.textContent (Js.Opt.return (Js.string "Hello world!")))

let testPortal () =
withContainers2 (fun c1 c2 ->
act (fun () ->
React.Dom.render
(div [||]
[ string "Hello"
; React.Dom.create_portal
(div [||] [ string "world!" ])
(Html.element c2)
])
(Html.element c1));
assert_equal c1##.innerHTML (Js.string "<div>Hello</div>");
assert_equal c2##.innerHTML (Js.string "<div>world!</div>"))

let testKeys () =
withContainer (fun c ->
act (fun () ->
Expand Down Expand Up @@ -766,6 +795,7 @@ let basic =
"basic"
>::: [ "testDom" >:: testDom
; "testReact" >:: testReact
; "testPortal" >:: testPortal
; "testKey" >:: testKeys
; "testOptionalPropsUppercase" >:: testOptionalPropsUppercase
; "testOptionalPropsLowercase" >:: testOptionalPropsLowercase
Expand Down

0 comments on commit 41ab37c

Please sign in to comment.