Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs: Set data- attributes on elements without JSX

Tags:

reactjs

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.

like image 404
DavidM Avatar asked Jul 15 '14 19:07

DavidM


People also ask

How do you set data attribute value in React JS?

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 .

Is it possible to use React without JSX?

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.

How do I add a custom attribute in 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.

Can you conditionally add attributes to components in React?

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.


1 Answers

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.

like image 168
DavidM Avatar answered Oct 25 '22 21:10

DavidM