This component allows you to render isomorphically!.
The trick is in defaultProps
and componentDidMount
methods.
- On the server, it fetches initial data as default props.
- On client, it does nothing, but in
componentDidMount
method, it fetches the same data as the server side.
And you get isomorphic React component for free here!.
import React from 'react';
import AppState from '../stores/app-state'
class PostsList extends React.Component {
constructor(props){
super(props)
this.state = {data: props.data}
}
componentDidMount(){
AppState("/lists", (data) => {
this.setState({data: data})
})
}
render(){
let y = this.state.data.map((x) => <div>{x.title}</div>)
return (
<div>
<p>Posts List </p>
{y}
</div>
)
}
}
PostsList.contextTypes = {
router: React.PropTypes.func.isRequired
}
PostsList.propTypes = {
data: React.PropTypes.array.isRequired
}
if (typeof window === 'undefined'){
AppState("/lists", (data) => {
PostsList.defaultProps = {data: data}
})
} else {
PostsList.defaultProps = {data: []}
}
export default PostsList;
You can checkout full book here