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.
<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
Data attributes also drive CSS. The state lives in React; the attribute simply exposes it to a stylesheet.
Syntax
<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-*andaria-*, React renderstrueas"true"andfalseas"false". For ordinary attributes such asdisabled,falseremoves the attribute instead. To remove a data attribute, passundefined. - Values are not data structures. To store an object, you would have to
JSON.stringifyit; in React you almost never need to. Pass the object through props or closures instead:onClick={() => select(user)}. - Testing hooks:
data-testidis 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, notdataUserName. In JavaScript writedataset.userName. - Selectors:
[data-state="on"]in CSS andquerySelector('[data-id="7"]')in scripts.
Related
aria-* attributes,className,style, Event handler props- Lessons: JSX in depth, Styling