Skip to content

Instantly share code, notes, and snippets.

@Junglecrew
Forked from chantastic/on-jsx.markdown
Last active March 11, 2018 23:59
Show Gist options
  • Save Junglecrew/d71dcb8b8397f1d3a21f90bd6c107d37 to your computer and use it in GitHub Desktop.
Save Junglecrew/d71dcb8b8397f1d3a21f90bd6c107d37 to your computer and use it in GitHub Desktop.
JSX, a year in

A component like this would be rejected in code review for having both a presentation and data concern:

// CommentList.js
import React from "react";

class CommentList extends React.Component {
  constructor() {
    super();
    this.state = { comments: [] }
  }
  
  componentDidMount() {
    fetch("/my-comments.json")
      .then(res => res.json())
      .then(comments => this.setState({ comments }))
  }
  
  render() {
    return (
      <ul>
        {this.state.comments.map(({ body, author }) =>
          <li>{body}-{author}</li>
        )}
      </ul>
    );
  }
}

It would then be split into two components. The first is like a traditional template, concerned only with presentation, and the second is tasked with fetching data and rendering the related view component.

// CommentList.js
import React from "react";

const Commentlist = comments => (
  <ul>
    {comments.map(({ body, author }) =>
      <li>{body}-{author}</li>
    )}
  </ul>
)
// CommentListContainer.js
import React from "react";
import CommentList from "./CommentList";

class CommentListContainer extends React.Component {
  constructor() {
    super();
    this.state = { comments: [] }
  }
  
  componentDidMount() {
    fetch("/my-comments.json")
      .then(res => res.json())
      .then(comments => this.setState({ comments }))
  }
  
  render() {
    return <CommentList comments={this.state.comments} />;
  }
}

In the updated example, CommentListContainer could shed JSX pretty simply.

  render() {
    return React.createElement(CommentList, { comments: this.state.comments });
  }

Additionally, a Higher-order Component or component with Render Props could help in making container components and stateless components more composeable

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