Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 662
abhishek gupta Avatar asked Oct 18 '25 03:10

abhishek gupta


1 Answers

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>;
like image 113
Armine Abramyan Avatar answered Oct 20 '25 16:10

Armine Abramyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!