Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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