Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data attribute of html element in react.js context

The CMS passes a variable as data-rest-url attribute to the React.js App:

<div id="reactjs-root" data-rest-url="http://my-ip-addess:8080/Rest-api-here">...</div>

If I add jQuery to my React.js App, then I can simply:

 componentWillMount() {
    const $reactRoot = $('#reactjs-root');
    const restUrl = $reactRoot.attr('data-rest-url');
 }

But adding jQuery just for this? How would you pass some variable from a CMS to your Single Page React App and read / parse / get it with react.js?

like image 453
nachtigall Avatar asked Mar 14 '17 10:03

nachtigall


People also ask

How do you get data attribute value in react JS?

Another method that is described below with code examples can be used to tackle the same issue React Get Data Attribute From Element. <div data-id={someId} >Test</div> const id = e. target. getAttribute("data-id"); //alternate to getAttribute const id = e.

How do you get a content of a certain HTML element in React?

Access a DOM Element Using ReactDOM.findDOMNode() . findDOMNode() is used to find a specific node from the DOM tree and access its various properties, such as its inner HTML, child elements, type of element, etc. In short, it can return all the supported DOM measurements related to the kind of element.

How do I display HTML data in react JS?

React's goal is in many ways to render HTML in a web page. React renders HTML to the web page by using a function called ReactDOM.render() .

How do you get data attribute from event React?

Use the target. dataset property to access data attributes from the event object in React. The dataset property provides read and write access to the custom data attributes of the element. The property returns a Map of strings which can be converted to an object.


2 Answers

const reactRoot = document.getElementById('reactjs-root');
const restUrl = reactRoot.getAttribute('data-rest-url');

Also, avoid using $ in your variable name. You're likely to run into a lot of libraries that conflict with the $ you have used as a variable.

like image 144
mehulmpt Avatar answered Sep 29 '22 22:09

mehulmpt


Consider passing your data attributes to your component as props instead of hard coding the root element ID within the component itself.

Rendering:

var rootElement = document.getElementById('reactjs-root');
ReactDOM.render(
  <YourComponent resturl={rootElement.getAttribute('data-rest-url')}></YourComponent>,
  rootElement
);

Within the component you can access the injected url:

componentWillMount() {
    console.log(this.props.resturl)
}

This makes for a more reusable component that is decoupled from a specific element ID.

like image 37
MrCode Avatar answered Sep 29 '22 22:09

MrCode