11/08/2018, 19:52
Isomorphic ReactJS Component
This post is a sample chapter from my upcoming book How to render a ReactJS component 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 ...
This post is a sample chapter from my upcoming book
How to render a ReactJS component 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;
Suppose:
- You use React-Router on both client and server
- You have a polyfill AppState to fetch data on both client and server:
export default AppState = (path) => { // if this is client {... your code here} // else if you're on server {... your code here} }
- You use ES6 syntax with React.JS
Then:
- When you make a http request to '/lists, the server first render the PostsList component with the props data fetched by AppState
- Once rendered in the browser, the componentDidMount will fetch data from server api to update its state data to match the initial rendered data.
So:
- If you view page source, you'll get full rendered html with initial data (it's called server-rendering)
- Your rendered React component is now a real React component with its life cycle. You can make anything you want from now.
- To test these things, simply disable Javascript on client, and refresh the page. You'll get the same result!
Please make any feedback and suggestions.
Thank you for reading.