How to append child to the body with Rescript

How to append child to the body with Rescript

Subscribe to my newsletter and never miss my upcoming articles

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

->Option.flatMap(document => document->HtmlDocument.body)
-> => {
  let root = document->Document.createElement("div", _)
  // ReactDOM.render(<App />, root) // if you are using react

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"
    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

let root = Document.createElement("div")

Element.appendChild(body, root)


Share this


Do share your feedback and suggestions

You can connect with me at Twitter | GitHub | LinkedIn

Proudly part of