Is there a right way to pass data into a React component from the HTML page? Is there a right way to pass data into a React component from the HTML page? reactjs reactjs

Is there a right way to pass data into a React component from the HTML page?


I have used data- attributes for various props, then passed all the props using destructuring {...dataset}, for example:

HTML:

<div id="app" data-feed='custom_feed.json' data-someprop='value'></div>

JS:

var root = document.getElementById('app');ReactDOM.render(<X {...(root.dataset)} />, root);

Edit: demo fiddle
Edit 2018: updated fiddle


I had a similar problem, dynamically generated pages that contain data relevant to the React stuff.

I just declared them in the global scope ..

<script>  window.foobles = [12,453,12];  window.bahs = ["bah", "bah", "black sheep"];</script>

.. THEN ..

ReactDOM.render(  <Component    foobles={window.foobles}    bahs={window.bah}  />,  document.getElementById('app'))

Obviously, from a namespacing perspective, this can have some drawbacks :)


You can just pass your data when mounting the component like so:

<div id="root"></div><script>    const data = { foo: 'bar' };    ReactDOM.render(        React.createElement(MyComponent, data),        document.getElementById('root')    );</script>