2

If I write this in JSX and render it with React:

<div data-foo>Hello world</div>

...the resulting DOM looks like this:

<div data-foo="true">Hello world</div>

Why?

For comparison, when I use standardised boolean attributes (e.g. <button disabled>OK</button>), this doesn't happen – the resulting DOM is the same as the JSX. Why are boolean data-attibutes treated differently?

callum
  • 34,206
  • 35
  • 106
  • 163
  • There's no such thing as a boolean `data-` attribute. They're strings as far as the DOM is concerned. – Pointy Jul 19 '17 at 14:43
  • @Pointy that contradicts https://stackoverflow.com/a/9729132/414825 – although you might be right, another answer argues it's wrong – callum Jul 19 '17 at 14:44
  • Yes it does; I think that answer is incorrect. [Here's some HTML5 documentation on the topic.](https://www.w3.org/TR/2010/WD-html5-20101019/elements.html#embedding-custom-non-visible-data-with-the-data-attributes) – Pointy Jul 19 '17 at 14:49
  • I'm not sure what React does with `data-` attributes, but for example the jQuery `.data()` API checks to see if the attribute value can be interpreted as JSON, and if so you get back the result of a JSON parse, and in the case of strings that look like JavaScript primitives (numbers and booleans) you get the parsed primitive value. – Pointy Jul 19 '17 at 14:52
  • Maybe, it works as designed. If you have a reason to not want this behaviour, you should open an issue in the Git repo. – vijayst Jul 19 '17 at 15:48
  • @vijayst – thanks, but it's not blocking me, and I have no reason to assume it's a bug, it just concerns me that I don't understand why it happens. – callum Jul 20 '17 at 12:51

0 Answers0