Skip to content
Tutorials Center
My learning

Topics

React Reference ยท Props and Attributes

React data-* attributes

Use data-* attributes in React: hyphenated names, how values are stringified, reading them through dataset, and when props or state are a better fit.

HTML allows you to attach your own information to any element with attributes that start with data-. React passes them through untouched. Like aria-*, they keep their hyphens in JSX: data-id, data-testid, data-state. They are handy for CSS selectors, automated tests and small hooks for non-React code.

JSX
<li data-id={user.id} data-status="active">{user.name}</li>

In the browser, element.dataset.id reads data-id; a name with several hyphens turns into camelCase (data-user-name becomes dataset.userName).

Try it

Reading data attributes in a handler

Data attributes also drive CSS. The state lives in React; the attribute simply exposes it to a stylesheet.

Styling from a data attribute

Syntax

JSX
<element data-name={value} />
Name Description
data-* Any attribute name that starts with data-, lowercase, with hyphens.
value A string or number. Booleans are written as "true" and "false". null and undefined remove the attribute.

Reading: element.dataset.camelCaseName always returns a string (or undefined when the attribute is missing). Convert with Number(...) where needed.

Usage notes

  • Booleans are strings. For data-* and aria-*, React renders true as "true" and false as "false". For ordinary attributes such as disabled, false removes the attribute instead. To remove a data attribute, pass undefined.
  • Values are not data structures. To store an object, you would have to JSON.stringify it; in React you almost never need to. Pass the object through props or closures instead: onClick={() => select(user)}.
  • Testing hooks: data-testid is a common convention for selecting elements in tests. Prefer queries by role and label first, and fall back to test ids.
  • Not for secrets. Everything in an attribute is visible in the page source.
  • Hyphens only in markup. In JSX write data-user-name, not dataUserName. In JavaScript write dataset.userName.
  • Selectors: [data-state="on"] in CSS and querySelector('[data-id="7"]') in scripts.