Skip to content

Instantly share code, notes, and snippets.

@pasupuletics
Last active April 16, 2017 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pasupuletics/55ddb0133392ebd6bbac164905611ebb to your computer and use it in GitHub Desktop.
Save pasupuletics/55ddb0133392ebd6bbac164905611ebb to your computer and use it in GitHub Desktop.
ReatJs Presentational and Container Components

A container does data fetching and then renders its corresponding sub-component. That’s it.

“Corresponding” meaning a component that shares the same name:

StockWidgetContainer => StockWidget
TagCloudContainer => TagCloud
PartyPooperListContainer => PartyPooperList

Why containers? Say you have a component that displays comments. You didn’t know about container components. So, you put everything in one place:

class CommentList extends React.Component {
  this.state = { comments: [] };

  componentDidMount() {
    fetchSomeComments(comments =>
      this.setState({ comments: comments }));
  }
  render() {
    return (
      <ul>
        {this.state.comments.map(c => (
          <li>{c.body}—{c.author}</li>
        ))}
      </ul>
    );
  }
}

Your component is responsible for both fetching data and presenting it. There’s nothing “wrong” with this but you miss out on a few benefits of React.

Reusability: CommentList can’t be reused unless under the exact same circumstances.

Our component is opinionated about data structure but has no way of expressing those opinions. This component will break silently if the json endpoint change.

First, lets pull out data-fetching into a container component.

class CommentListContainer extends React.Component {
  state = { comments: [] };
  componentDidMount() {
    fetchSomeComments(comments =>
      this.setState({ comments: comments }));
  }
  render() {
    return <CommentList comments={this.state.comments} />;
  }
}

Now, let’s rework CommentList to take comments as a prop.

const CommentList = props =>
  <ul>
    {props.comments.map(c => (
      <li>{c.body}—{c.author}</li>
    ))}
  </ul>

We’ve separated our data-fetching and rendering concerns. We’ve made our CommentList component reusable. We’ve given CommentList the ability to set PropTypes and fail loudly.

Source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment