HTML/JSX data-attributes

Hi, is there a plan to fix the JSX data-attributes issue in version 12 (or at all) of ReScript?

The documentation only shows nightmarish hacks for adding data attributes (Components and Props | React handling-invalid-prop-names-eg-keywords ), but this is unusable in the case of large design systems/component packages that rely on data attributes (ex. for CSS manipulation)

Hi. You should be able to achieve a better usage for data attributes with JSX using a generic JSX transformer. For example:

module Elements = {
  let propsToAttrs = props => {
    let attrs = []

    switch props.data {
    | None => ()
    | Some(dataObj) => {
        %raw(`
          Object.entries(dataObj).forEach(([key, value]) => {
            attrs.push(`data-${key}`, value)
          })
        `)
      }
    }

    attrs
  }
}

Then you can do:

<div data={
  "user-id": 123,
  "role": "admin",
  "active": true
}>
  { React.String("User Card") }
</div>

/* This will render as: */
<div class="card" data-user-id="123" data-role="admin" data-active="true">
  User card
</div>

You still have to use raw JS because of the dashes (let me know if anyone has a better suggestion). I also haven’t tried generic JSX transform with ReScript React though.

If you want to check a JSX transform implementation example, I added support to data attributes in Xote, a UI lib I’m working on for ReScript: https://github.com/brnrdog/xote/blob/main/src/Xote__JSX.res

1 Like

V12 does not have anything extra for this, but it’s an interesting topic and definitely something we should explore if/how we can solve in a good way.

We’ve also talked about local-only extensions of the DOM props as well. Also related.

5 Likes