Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dom: add create_portal #158

Merged
merged 1 commit into from
Mar 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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