Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/36545118/is-there-a-right-way-to-pass-data-into-a-react-component-from-the-html-page

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...