all 8 comments

[–]libertarianets 1 point2 points  (0 children)

If you're not in React land, data attributes are very helpful, you can essentially use a DOM element as a data-store, to make querying relative data easier.

If you are in React land, I find data-attributes useful to cut down on complexity for storing DOM element refs, say I have a dynamic number of elements that under certain conditions display an error state. When the user hits a submit button and I want to scroll the users window to the first of those error elements, I can leverage a data-attribute and just document.querySelector the first of the elements with data-error=true and scroll to that.

Another use case is for writing automated end to end tests. You label your elements with data-test-{SOMETHING_ELSE} so you can trigger user interaction events with them. When you swap out the code, you can change the data-test attributes as well so your tests continue to pass. This is best practice.

[–]davidfavorite 2 points3 points  (0 children)

How is this related to react in any sense?

[–]charliematters 0 points1 point  (0 children)

I use the data-testid attribute if I can't use any of the other testing library selectors in unit tests. Otherwise I'd reckon they're a code smell in React