Answer a question

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?

Answers

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.

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐