abhishek gupta
abhishek gupta

Reputation: 80

get data attribute from “root” DOM node in react js

Let’s say there is a <div> somewhere in HTML file:

I want to pass an attribute data-person-name from that <div> having id root,to react element

<div id="root" data-person-name="John"></div>
const element = <h1>Hello,{data-person-name}</h1>;
ReactDOM.render(element, document.getElementById('root'));

Please suggest the right way to do that.

Upvotes: 4

Views: 5179

Answers (1)

Armine Abramyan
Armine Abramyan

Reputation: 117

A cleaner way would be to prefix all custom attributes with "data-". Because there is no known attribute "personName" for a div element and having that is against W3 rules. The code may look like this:

<div id="root" data-personName="John"></div>
const element = <h1>Hello,{document.getElementById('root').getAttribute('data-personName')}</h1>;

Upvotes: 4

Related Questions