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

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 :)


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


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>

React Habitat is a framework that facilitates this if you want something reusable and extendable.

You register React components like this

containerBuilder.register(Feed).as('Feed')

Then define targets in the HTML like this with props

<div data-component="Feed" data-prop-feed-src="/custom_feed.json">

React Habitat will wire these up any time it appears in the HTML.

Disclosure: I am one of the head maintainers of this framework.

Tags:

Reactjs