Getting data attribute of html element in react.js context
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.
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.