Quantcast
Channel: ReScript Forum - Latest posts
Viewing all articles
Browse latest Browse all 2592

HTML/JSX data-attributes

$
0
0

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


Viewing all articles
Browse latest Browse all 2592

Trending Articles