10

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?

3
  • 1
    You don't need jQuery for that. Plain vanilla JavaScript works fine. document.getElementById('reactjs-root').dataset.restUrl. Commented Apr 12, 2018 at 8:21
  • @Fred Sure, but it's harder to read and more error-prone (browser quirks): In general, I prefer to use the facade jQuery which handles all edge cases. Commented Apr 12, 2018 at 12:33
  • With React you usually don't really have any need for jQuery so if all you want to do is get an attribute from an element then its much better to solve that using plain JavaScript. Commented Apr 12, 2018 at 13:09

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, that's a slightly better approach even. Good idea.
5
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.

1 Comment

Instead of the getAttribute method, you can use the dataset property.

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.