Every React app I've made (which is actually only one small one) uses the actions up, data down
approach, where (as I understand it) components receive data from parent components by calling this.props.somePropertyName
. I'm now trying out react-router and none of the examples given seem to have child components receive data via props
and, from what I can see, there's no easy to pass props to child components (other than the <RouteHandler/>
. In the example below, I pass an endpoint to the HomePage component from the App. In the HomePage component, I get the data (a list of blog posts) and wish to pass individual post to the PostDetail component (as a prop) but I can't do it. I don't want to pass all the data using react-router "params" because whatever gets passed as in params ends up in the url.
Question: In the code below, how do I pass data to the linked to PostDetail components, so I can call things like this.props.postBody
in the PostDetail component?
var App = React.createClass({
render: function(){
return (
<div>
<RouteHandler source="/my-api-data-source/"/>
</div>
)
}
})
var routes = (
<Route name="main path="/" handler={App}>
<DefaultRoute name="homepage" handler={HomePage}>
<Route name="post" path=":postId" hander={PostDetail}>
</Route>
)
var HomeComponent = React.createClass({
componentDidMount: function(){
$.get(this.props.source, function (result){
if(this.isMounted()){
this.setState({
posts: result
})
}
}
}
render: function(){
return (
//code omitted --I loop through posts array to create a list of links to posts like this
<ul>
<li>Link to "post" params={postId: somePostId}>post.title</li>
<li>Link to "post" params={postId: somePostId}>post.title</li>
<li>Link to "post" params={postId: somePostId}>post.title</li>
</ul>
)
}
})
Question: how do I pass data to the linked to PostDetail components, so I can call things like this.props.postBody
in the PostDetail component? (Also, imagine that I had several different routes and wanted to pass different props to different routes)
var PostDetail = React.createClass({
render: function(){
return (
<div>
<h2>want to call `this.props.title` here </h2>
want to call `this.props.postBody` here
want to call `this.props.postComments` here etc
</div>
)
}
)}
Note, my question is not a duplicate of this question as the props
in my question are coming from the HomePage route i.e. I can't wrap the PageDetail component with the HomePage component as a way to pass the props from HomePage to PageDetail (as is suggested by the SO answer I linked to)