4

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.

6
  • 1
    Is this name supposed to change dynamically ? Commented May 13, 2020 at 11:39
  • Note that personName is an invalid attribute for div elements. If you want to add non-DOM information to elements, use a data-* attribute (e.g., data-person-name). Commented May 13, 2020 at 11:42
  • I'm afraid it's not clear what you're asking. You can get the element via document.getElementById("root") and get its attribute value via getAttribute("attribute-name-goes-here"). But this feels like an X/Y problem. Why do you want to take an attribute value and use it in a React element? Commented May 13, 2020 at 11:44
  • @T.J.Crowder I am rendering an input component on that Div, I have to send placeholder on basis of some condition, in data-person-name.So for that purpose, I need to do that Commented May 13, 2020 at 12:05
  • Sorry, I still don't get it. Normally you wouldn't use attributes like that in React. You'd pass props through the hierarchy instead. Commented May 13, 2020 at 12:23

1 Answer 1

4

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>;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @arm, it worked for me, but is there any other way for doing this.
if you want to pass personName by data attribute, I think there is no better way. But you can use localStorage instead: In App.js you can set personName: localStorage.setItem('personName', 'John'); and then use that value from anywhere: localStorage.getItem('personName');
Thanks @arm for the solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.