Search code examples
reasonreason-react

Pass arguments to rendered element from HTML


I have a component that I render on HTML based on class, with the function renderToElementWithClassName. I know I can pass values to component in the function (renderToElementWithClassName(<FAQ param="value" />, "class");. However, I need to be able to pass it on HTML, as it will be used in various places. Something like this:

<body>
    <div class="class" data-param="value" />
</body>

Is it possible?


Solution

  • After struggling with the code I finally got a hack to do this. Don't know if there's a better way, but this is what I did. You have to put this snippet inside the specific component you want to inject data-attributes:

    [@bs.val] [@bs.scope "document"]
    external querySelectorAll : string => array(Dom.element) = "";
    
    let renderByQuery = (query: string) => {
        let elements = querySelectorAll(query);
    
        elements |> Js.Array.forEach(e => {
            let yp = (e |> ReactDOMRe.domElementToObj)##dataset##yourprop;
            ReactDOMRe.render(ReasonReact.element(make(~yourProp={yp}, ())), e);
        });
    };
    

    Then, in your main file:

    YourComponent.renderByQuery(".custom_class");
    

    Now, in your HTML you can use data-attributes according with the ones you've set in the render function.

    <div class="custom_class" data-yourprop="value1"></div>
    <div class="custom_class" data-yourprop="value2"></div>
    

    This will render the same component with different yourProp props.