How to append child to the body with Rescript

May 25, 2021 · 2 min read · 8 views

When you're learning rescript, you would want to render your Reactjs app to a DOM node. It is not as simple as ReactDom.render(<App/>, #root).

Here is how you can do it.

First, go ahead install bs-webapi by running this command

npm install --save bs-webapi

Add the entry to bsconfig.json

"bs-dependencies": ["bs-webapi"],

use the following snippet

open Webapi.Dom
open Belt

document
->Document.asHtmlDocument
->Option.flatMap(document => document->HtmlDocument.body)
->Option.map(body => {
  let root = document->Document.createElement("div", _)
  root->Element.setId("app")
  // ReactDOM.render(<App />, root) // if you are using react
  root->Element.appendChild(body)
})
->ignore

Edit: We can also write our own bindings for maintainability as suggested by Patrick Ecker over here

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"
    @send external createElement: (t, string) => Dom.element = "createElement"
  }
}

open Webapi

let body = {
  open Document
  document->body
}

let root = Document.createElement("div")

Element.appendChild(body, root)

Playground