Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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?

like image 410
superluminary Avatar asked Apr 11 '16 09:04

superluminary


2 Answers

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

like image 97
pawel Avatar answered Sep 30 '22 08:09

pawel


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

like image 40
Sp4cecat Avatar answered Sep 30 '22 09:09

Sp4cecat