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.
To set a data attribute on an element in React, set the attribute directly on the element, e.g. <button data-test-id="my-btn"> or use the setAttribute() method, e.g. el. setAttribute('data-foo', 'bar') . You can access the element on the event object or using a ref .
JSX is not a requirement for using React. Using React without JSX is especially convenient when you don't want to set up compilation in your build environment. Each JSX element is just syntactic sugar for calling React.
To add custom HTML attributes in React, we can just add them as we do with regular HTML element attributes. We just add the custom-attribute custom attribute and it'll be rendered in the HTML. This works since React 16.
You can use any logic and conditionals in order to build the object. You will most commonly use the ternary operator to add conditional attributes to an element in React.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With