Search code examples
reactjsdomreasonreason-react

Render multiple components based on data attributes


On ReasonReact, if I want to render a specific element on a HTML element by id I can use the built-in function renderToElementWithId(ReasonReact.reactElement, Dom.element), for example:

ReactDOMRe.renderToElementWithId(<MyComponent />, "myComponent");

I have multiple <input /> HTML tags, and I want it to be rendered in every <input /> which has a specific data attribute. More specifically, I want that each input which has data-type="tags" on it be rendered by <MyComponent />. On Javascript we could do something like document.querySelectorAll("[data-type=tags]") and iterate the result rendering the components.

Although, I can't find anywhere in the documentation of ReasonReact nor BSB about how to do this. Can someone help me?

Thanks, in advance.


Solution

  • ReasonReact has a ReactDOMRe.render function that takes a Dom.element. You can then define querySelectorAll yourself, if you wish:

    [@bs.val] [@bs.scope "document"]
    external querySelectorAll : string => Dom.element = "";
    
    querySelectorAll("[data-type=tags]")
    |> Js.Array.forEach(element => ReactDOMRe.render(<MyComponent />, element));
    

    Or you can use bs-webapi, which gives you querySelectorAll along with a whole heap of other DOM functions if you need them.