Jump to Categories

Container components

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

Consider the following component that contains the logic for both recieving and outputting the data.

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>
    );
  }
}

A Container Component breaks up the data-fetching and make a seperate component to output that data.

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

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

Benefits

  • Seperating data-fetching and rendering
  • Can reuse the component that outputs the data
  • Ability to force an error if the PropTypes are not passed - or passed incorrectly

Refs

<a href="https://medium.com/@learnreact/container-components-c0e67432e005">Component slots</a> - Container Components<br>

</p>