Reputation: 178
I have 2 React Classes:
const PostList = React.createClass({
getInitialState: function () {
return {
status: "loading",
posts: []
}
},
render: function() {
return (
<div id="container">
<ReactRouter.Link to="upload"></ReactRouter.Link>
<a href="#/upload">{this.state.status}</a>
{
this.state.posts.map(function (post) {
return (
<Post post={post} />
);
})
}
</div>
);
}
});
const Upload = React.createClass({
render: function() {
return (
<div className="upload">Upload</div>
);
}
})
const MainContent = React.createClass({
render: function() {
return (
<div>
<Header />
<div id="inner-content">
{this.props.children}
</div>
<Footer />
</div>
);
}
})
const routes = (
<Route path="/" component={MainContent}>
<ReactRouter.IndexRoute component={PostList} />
<Route path="upload" component={Upload} />
</Route>
)
var render = ReactDOM.render(<Router history={History}>{routes}</Router>, document.getElementById("content"));
The question is how can i access the setState function on PostList to render new posts?
Posts will be refreshed through socket.io conenction so when a new posts arrives, i just want to set the state of the PostList to rerender the full html code with he new post(s)
Sorry for bad english...
Upvotes: 0
Views: 1553
Reputation: 53219
Add componentDidMount
function and set up a socket listener inside it such that when a new message arrives, add it to the current list of posts
const PostList = React.createClass({
getInitialState: function () {
return {
status: "loading",
posts: []
}
},
componentDidMount: function () {
var that = this;
// Be sure to set up data fetching code here
// Set up listener for posts updates here
socket.on('update', function (data) {
// Assuming data contains the post content
that.setState({
posts: that.state.posts.concat(data)
});
});
},
render: function() {
return (
<div id="container">
<ReactRouter.Link to="upload"></ReactRouter.Link>
<a href="#/upload">{this.state.status}</a>
{
this.state.posts.map(function (post) {
return (
<Post post={post} />
);
})
}
</div>
);
}
});
Upvotes: 1