How to manipulate DOM correctly?


#1

Hi all

I have the following component, that do dom manipulation.

let component = ReasonReact.statelessComponent("LinkRipple");

let make = (~onClick: 'a => unit, ~cssClass: string, ~color: string, children) => {
  /*
   * Determine the coordinates for ripple effect
   * At the end, it will execute the click function
   */

  let onLinkClicked = e => {
    let dom = External.convertToDomElement(e->ReactEvent.Mouse.currentTarget);
    let rect = Webapi.Dom.Element.getBoundingClientRect(dom);

    let x = ReactEvent.Mouse.pageX(e) - Webapi.Dom.DomRect.left(rect);
    let y = ReactEvent.Mouse.pageY(e) - Webapi.Dom.DomRect.top(rect);

    let rippleDiv =
      Webapi.Dom.Document.createElement("div", Webapi.Dom.document);
    let domTokenList = Webapi.Dom.Element.classList(rippleDiv);

    Webapi.Dom.DomTokenList.add("ripple", domTokenList);
    Webapi.Dom.Element.setAttribute(
      "style",
      "top:" ++ string_of_int(y) ++ "px; left:" ++ string_of_int(x) ++ "px;",
      rippleDiv,
    );
    Webapi.Dom.Element.appendChild(rippleDiv, dom);

    Js.Global.setTimeout(
      () => {
        onClick();
        Webapi.Dom.Element.removeChild(rippleDiv, dom) |> ignore;
      },
      300,
    )
    |> ignore;
  };

  {
    ...component,
    render: _self =>
      <a onClick=onLinkClicked className=cssClass> children </a>,
  };
};

As you can see on the code, when the user click on the link tag, the function onLinkClicked will manipulate the DOM. Inside the function, another function from the property onClick(); will be executed. When I place the function onClick(); outside the Js.Global.setTimeout the DOM manipulation does not work correctly.
The question is, how to do manipulate DOM correctly? DOM I have to manipulate virtual DOM?

THANKS