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 13, 2022
1 parent 831f451 commit 23773bf
Show file tree
Hide file tree
Showing 2 changed files with 35 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 @@ -48,6 +48,15 @@ val render_to_element_with_id : Core.element -> string -> unit
| 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
26 changes: 26 additions & 0 deletions test/test_ml.ml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@ 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 @@ -47,6 +59,19 @@ 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 @@ -784,6 +809,7 @@ let basic =
"basic"
>::: [ "testDom" >:: testDom
; "testReact" >:: testReact
; "testPortal" >:: testPortal
; "testKey" >:: testKeys
; "testOptionalPropsUppercase" >:: testOptionalPropsUppercase
; "testOptionalPropsLowercase" >:: testOptionalPropsLowercase ]
Expand Down

0 comments on commit 23773bf

Please sign in to comment.