Skip to content

Instantly share code, notes, and snippets.

@ryanbrunner
Created October 4, 2016 23:34
Show Gist options
  • Save ryanbrunner/0b4701b39019c2ee11788235b3b1adf0 to your computer and use it in GitHub Desktop.
Save ryanbrunner/0b4701b39019c2ee11788235b3b1adf0 to your computer and use it in GitHub Desktop.

A basic React component

var ComponentName = React.createClass({
  render: function() {
    return <div>My Component</div>
  }
});

React methods

  • render - This function should return the HTML structure of the component given the props and state of a component.

    render: function() {
      return <div>Hi, { this.props.name }</div>
    }
    
  • getInitialState - Returns 'defaults' for state. Just return a simple object here, if you need to make server calls, use componentWillMount

    getInitialState: function() {
      return {
        bool: true,
        array: [1,2,3]
      }
    }
    
  • getDefaultProps - Initialize props to default values if props aren't provided.

React Lifecycle events

  • componentWillMount - Called before the component renders itself. Not many good uses.

  • componentDidMount - Called when a component has been added to the DOM. Do your initial AJAX calls here.

  • componentWillReceiveProps - Called when the props of a component are about to change. If you need to set state based on prop changes, do it here. Also good if prop change requires navigating to different areas.

  • shouldComponentUpdate - Return false from here to prevent re-rendering. You should only return false if no props have changed. Usually implemented to solve performance problems.

  • componentWillUpdate - You have access to the new props and new state here. You can't modify either though.

  • componentDidUpdate - Called after rendering is complete. Put side-effects (attaching 3rd party libraries, etc) here.

  • componentWillUnmount - Called when a component is about to be removed. Clean-up code goes here.

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