... in react kotl" /> ... in react kotl" /> ... in react kotl"/>

Adding custom data-* attributes to tags while using the new(non-legacy) kotlin react wrappers

100 Views Asked by At

What's the equivalent of this:

<article
  id="electric-cars"
  data-columns="3"
  data-index-number="12314"
  data-parent="cars">
...
</article>

in react kotlin dsl non-legacy wrapper.

1

There are 1 best solutions below

0
Richard Domingo On

The default solution is to use extensions.

    private const val DATA_COLUMNS_KEY: String = "data-columns"

    var HTMLAttributes<*>.dataColumns: Int
      get() = asDynamic()[DATA_COLUMNS_KEY]
      set(value) {
        asDynamic()[DATA_COLUMNS_KEY] = value
      }

and the way you use it:

    div {
      dataColumns = 3
    }

Explanation:

The way it works is you create an extension for HTMLAttributes<*> and create a setter for it. Since the setter will be using asDynamic it will include the property in the react html dom element.

Disclaimer: I got this answer from kotlin slack group :)