16

React supports data-* and aria-* attributes on elements. When using the component API, I would guess these attributes could be set just like the rest:

React.DOM.div({style: {...}, dataMyFoo: 'bar'}, ...)

Nope. That doesn't work. The dataMyFoo attribute is silently ignored. I read somewhere that these need to be all lowercase. How about:

React.DOM.div({style: {...}, datamyfoo: 'bar'}, ...)

Again, silently ignored.

Is this possible? If so, what is the secret? I spent quite a while searching without finding the answer.

1 Answer 1

27

The answer, it turns out, is to use hyphen-separated all lowercase names for the data attribute, like so:

React.DOM.div({style: {...}, 'data-my-foo': 'bar'}, ...)

Note that you must quote the attribute name in this case, since hyphens are not allowed in identifiers in Javascript.

4
  • 3
    Yes, this is correct. We're considering moving to a dataSet: {myFoo: 'bar'} model in the future, which would put data-my-foo="bar" into the DOM. This follows closely the DOM API for accessing data attributes. Jul 16, 2014 at 20:03
  • 2
    @PaulO'Shannessy that sounds perfect. One of the things I initially tried was data: {myFoo: 'bar'} so this closely follows what I was naturally inclined to do.
    – DavidM
    Jul 16, 2014 at 21:14
  • What about data-* attributes that have no value? should you just do { 'data-foo-bar': true }? or something else? Dec 9, 2014 at 3:30
  • 2
    I'm on v0.12.1. {'data-foo-bar': true} renders as <... data-foo-bar="true"> whereas {'data-foo-bar': ''} renders as <... data-foo-bar> so I might go with that.
    – DavidM
    Dec 17, 2014 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.