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?
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.
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.
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() .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With