Skip to content

Instantly share code, notes, and snippets.

@eiriklv
Created September 20, 2018 06:55
Show Gist options
  • Save eiriklv/d3d241fe89b832f50303390fa065fd6c to your computer and use it in GitHub Desktop.
Save eiriklv/d3d241fe89b832f50303390fa065fd6c to your computer and use it in GitHub Desktop.
Component class conventions

React Conventions

  • Method ordering
  • PropTypes + DefaultProps
  • Destructuring from props and state (intent)
  • Avoid instance methods (only for things that matters to React)
  • Components > render methods (renderElements/renderItems/etc)
  • Pure render function (no window or Math.random())
  • Containers (connected) vs. Presentational Components (pure)
  • Functional stateless > createClass / class
  • Composition > Inheritance (Higher order components for adding functionality without coupling)
/**
 * Using .createClass
 */
const MyComponent = React.createClass({
  propTypes: {},

  getDefaultProps() {},
  getInitialState() {},

  componentWillMount() {},
  componentDidMount() {},
  componentWillReceiveProps() {},
  shouldComponentUpdate() {},
  componentDidUpdate() {},

  handleSomeThing() {},
  handleSomeThingElse() {},

  render() {
    const { ... } = this.props;
    const { ... } = this.state;

    if (error) {
      return <div>error</div>;
    }

    if (loading) {
      return <div>loading..</div>;
    }

    return (
      <div>Success!</div>
    );
  }
});

module.exports = MyComponent;
/**
 * Using ES6 class syntax
 */
class MyComponent extends React.Component {
  constructor() {}

  componentWillMount() {},
  componentDidMount() {},
  componentWillReceiveProps() {},
  shouldComponentUpdate() {},
  componentDidUpdate() {},

  handleSomeThing() {},
  handleSomeThingElse() {},

  render() {
    const { ... } = this.props;
    const { ... } = this.state;

    if (error) {
      return <div>error</div>;
    }

    if (loading) {
      return <div>loading..</div>;
    }

    return (
      <div>Success!</div>
    );
  }
});

module.exports = MyComponent;
/**
 * Using a functional stateless component
 */
function MyComponent({ ... }) {
  if (error) {
    return <div>error</div>;
  }

  if (loading) {
    return <div>loading..</div>;
  }

  return (
    <div>Success!</div>
  );
});

module.exports = MyComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment