I have a React app like this.
var X = React.createClass({ componentDidMount: function() { fetch(this.props.feed).then(...); } render: function() { return <div>{this.props.feed}</div> } });
The feed prop is used to get a JSON feed in componentDidMount that's unique for a particular customer.
It would be convenient to pass data into my React app from the HTML to parameterise it:
<html> <body> <div id="app" feed='custom_feed.json'></div> </body> </html
My current solution looks like this:
var root = document.getElementById('app'); var feed = root.getAttribute('feed') ReactDOM.render(<X feed={feed}/>, root);
This obviously works, but it feels like there ought to be a more idiomatic solution. Is there a more React way to do this?
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With