Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ReactJS - The Container component pattern

ReactJS - The Container component pattern

A short slide for ReactJS workshop.

Khánh Trần

October 25, 2016
Tweet

More Decks by Khánh Trần

Other Decks in Programming

Transcript

  1. Container Components? A container does data fetching and then renders

    its corresponding sub-component. That’s it. — - Jason Bonta • StockWidgetContainer => StockWidget • TagCloudContainer => TagCloud
  2. Why containers? // CommentList.js class CommentList extends React.Component { constructor()

    { super(); this.state = { comments: [] } } componentDidMount() { $.ajax({ url: "/my-comments.json", dataType: 'json', success: function(comments) { this.setState({comments: comments}); }.bind(this) }); } render() { return <ul> {this.state.comments.map(renderComment)} </ul>; } renderComment({body, author}) { return <li>{body}—{author}</li>; } }
  3. Reusability CommentList can’t be reused unless under the exact same

    circumstances. • Top Customer Reviews vs. Most Recent Customer Reviews
  4. Data structure Your markup components should state expectations of the

    data they require. PropTypes are great for this. — - Learn React with chantastic
  5. This time with a container // CommentListContainer.js class CommentListContainer extends

    React.Component { constructor() { super(); this.state = { comments: [] } } componentDidMount() { $.ajax({ url: "/my-comments.json", dataType: 'json', success: function(comments) { this.setState({comments: comments}); }.bind(this) }); } render() { return <CommentList comments={this.state.comments} />; } }
  6. Let's rework on CommentList to get comments as a prop

    // CommentList.js class CommentList extends React.Component { constructor(props) { super(props); } render() { return <ul> {this.props.comments.map(renderComment)} </ul>; } renderComment({body, author}) { return <li>{body}—{author}</li>; } }
  7. So, what did we get? • We’ve separated our data-fetching

    and rendering concerns. • We’ve made our CommentList component reusable. • ...next >
  8. ...we’ve given CommentList the ability to set PropTypes and fail

    loudly CommentList.propTypes = { comments: React.PropTypes.object.isRequired }
  9. Q&A