How to append child to the body with rescript

1 Like

Tip: It’s oftentimes easier maintaining your own Webapi bindings and copy paste the relevant bits from projects like rescript-webapi. Very easy to adapt the code to your actual needs without hidden runtime code (= cleaner JS output). It’s also easier to navigate / find the code you are interested in.

Most importantly… you don’t need to read old Reason code.

Here’s a simple example:

module Webapi = {
  module Element = {
    @set external setId: (Dom.element, string) => unit = "id"
    @send
    external appendChild: (Dom.element, Dom.element) => unit = "appendChild"
  }

  module Document = {
    @val external document: Dom.document = "document"
    @get external body: Dom.document => Dom.element = "body"
    @val external createElement: string => Dom.element = "createElement"
  }
}

open Webapi

let body = {
  open Document
  document->body
}

let root = Document.createElement("div")

Element.appendChild(body, root)

Resulting in the following JS:

var body = document.body;

var root = createElement("div");

body.appendChild(root);

Playground Link

2 Likes

Thanks for the tip. I’ve also updated the article.

Hi @arbaaz.

There is an issue in the above bindings.

This should have been

 @send external createElement: (t, string) => Dom.element = "createElement"

playground

1 Like

thanks buddy, updated.