1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Isomorphic ReactJS component

Posted at

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

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?