React Cheat Sheet v15.5

render

react-dom
import { render } from "react-dom";

render(
  <MyComponent />,
  document.getElementById("component-root")
);

findDOMNode

react-dom
import { findDOMNode } from "react-dom";

ReactDOM.findDOMNode(componentRef);

unmountComponentAtNode

react-dom
import { unmountComponentAtNode } from "react-dom";

ReactDOM.unmountComponentAtNode(document.getElementById('MyComponent'))

renderToString

react-dom/server
import { renderToString } from "react-dom/server";
ReactDOMServer.renderToString(<MyComponent />);

renderToStaticMarkup

react-dom/server
import {renderToStaticMarkup} from "react-dom/server";
renderToStaticMarkup(<MyComponent />);

Component

react
class MyComponent extends React.Component {
  render() {
    return <div />;
  }
}

PureComponent

react
class MyComponent extends React.PureComponent {
  render() {
    // only updates props and state have not changed.
    // uses a shallow compare.

    return <div />;
  }
}

createElement

react
React.createElement('div', props, children); // tag name

React.createElement(MyComponent, props, children); // React Component type

cloneElement

react
React.cloneElement(element, props, ...children);

createFactory

react
React.createFactory('div'); // tag name;

React.createFactory(MyComponentClass); // React Component type

isValidElement

react
React.isValidElement(MyComponent);

Children.map

react
React.Children.map(this.props.children, (child, i) => {
    return child;
})

Children.forEach

react
React.Children.forEach(this.props.children, (child, i) => {
  console.log(child + ' at index: ' + i);
})

Children.count

react
React.Children.count(this.props.children);

Children.only

react
React.Children.only(this.props.children);

Children.toArray

react
React.Children.toArray(this.props.children)

setState (object)

react
// good for static values

this.setState({mykey: 'my new value'});

setState (function)

react
// good for state transitions

this.setState((prevState, props) => {
  return {count: prevState.count + props.step};
});

setState (optional callback)

react
// fires after setState
// prefer componentDidUpdate

this.setState(
  (prevState, props) => ({ count: prevState.count + props.step }),
  () => console.log(this.state.count)
);

forceUpdate

react
// forces a re-render; AVOID if possible

this.forceUpdate();

Context (example)

react
// requires 'prop-types' library

import { string } from "prop-types";

class Cowboy extends React.Component {
  childContextTypes: {
    salutation: string
  }

  getChildContext() {
    return { salutation: "Howdy" };
  }

  render() {
    return React.Children.only(this.props.children);
  }
}

var Greeting = React.createClass({
  contextTypes: {
    salutation: string
  },

  render: function () {
    return <div>{this.context.salutation} {this.props.name}.</div>
  }
});

// <Greeting name="Michael" />
// => Michael.

// <Cowboy><Greeting name="Michael" /></Cowboy>
// => Howdy Michael.

contextTypes

react
// add to the context-aware component
// requires 'prop-types' library

contextTypes: {
  color: PropTypes.string
},

childContextTypes

react
// add to the context provider
// requires 'prop-types' library

childContextTypes: {
  color: PropTypes.string
},

getChildContext

react
// add to the context provider

getChildContext() {
  return {color: "purple"};
}

render

react
render() {
  return <div />;
}

displayName

react
displayName: "MyComponent"

Lifecycle methods

react
namecalled forreceives contextsetState() triggers an update
componentWillMountinitial render()nono
componentDidMountinitial render()noyes
componentWillReceivePropsnew propsyesyes
shouldComponentUpdatenew props/stateyesyes
componentWillUpdatenew props/stateyesn/a
componentDidUpdatenew props/statenoyes
componentWillUnmountunmountingnon/a

componentWillMount

react
componentWillMount() {
  // invoked once.
  // fires before initial 'render'
}

componentDidMount

react
componentDidMount() {
  // good for AJAX: fetch, ajax, or subscriptions.

  // invoked once (client-side only).
  // fires before initial 'render'
}

componentWillReceiveProps

react
componentWillReceiveProps(nextProps) {
  // invoked every time component is recieves new props.
  // does not before initial 'render'
}

shouldComponentUpdate

react
shouldComponentUpdate(nextProps, nextState) {
  // invoked before every update (new props or state).
  // does not fire before initial 'render'.
}

componentWillUpdate

react
componentWillUpdate(nextProps, nextState) {
  // invoked immediately before update (new props or state).
  // does not fire before initial 'render'.

  // (see componentWillReceiveProps if you need to call setState)
}
✖ this.setState

componentDidUpdate

react
componentDidUpdate(prevProps, prevState) {
  // invoked immediately after DOM updates
  // does not fire after initial 'render'
}

componentWillUnmount

react
componentWillUnmount() {
  // invoked immediately before a component is unmounted.
}

PropTypes.array

prop-types
import { array } from "prop-types";

MyComponent.propTypes = {
  optionalArray: array,
  requiredArray: array.isRequired
}

PropTypes.bool

prop-types
import { bool } from "prop-types";

MyComponent.propTypes = {
  optionalBoolean: bool,
  requiredBoolean: bool.isRequired
}

PropTypes.func

prop-types
import { func } from "prop-types";

MyComponent.propTypes = {
  optionalFunction: func,
  requiredFunction: func.isRequired
}

PropTypes.number

prop-types
import { number } from "prop-types";

MyComponent.propTypes = {
  optionalNumber: number,
  requiredNumber: number.isRequired
}

PropTypes.object

prop-types
import { object } from "prop-types";

MyComponent.propTypes = {
  optionalObject: object,
  requiredObject: object.isRequired
}

PropTypes.string

prop-types
import { string } from "prop-types";

MyComponent.propTypes = {
  optionalString: string,
  requiredString: string.isRequired
}

PropTypes.node

prop-types
import { node } from "prop-types";

MyComponent.propTypes = {
  optionalNode: node,
  requiredNode: node.isRequired
};

// anything that can be rendered

PropTypes.element

prop-types
import { element } from "prop-types";

MyComponent.propTypes = {
  optionalElement: element,
  requiredElement: element.isRequired
}

PropTypes.instanceOf

prop-types
import { instanceOf } from "prop-types";

MyComponent.propTypes = {
  optionalClass: instanceOf(SomeClass),
  requiredClass: instanceOf(SomeClass).isRequired
}

PropTypes.oneOf

prop-types
import { oneOf } from "prop-types";

MyComponent.propTypes = {
  optionalEnum: oneOf(['Thing 1', 'Thing 2']),
  requiredEnum: oneOf(['Thing 1', 'Thing 2']).isRequired
}

PropTypes.oneOfType

prop-types
import { oneOfType, bool, string } from "prop-types";

MyComponent.propTypes = {
  optionalUnion: oneOfType([ bool, string ]),

  requiredUnion: oneOfType([ bool, string ]).isRequired,
}

PropTypes.arrayOf

prop-types
import { arrayOf, string } from "prop-types";

MyComponent.propTypes = {
  optionalArrayOfStrings: arrayOf(string),
  requiredArrayOfStrings: arrayOf(string).isRequired
}

PropTypes.objectOf

prop-types
import { objectOf, string } from "prop-types";

MyComponent.propTypes = {
  optionalObjectOfStrings: objectOf(string),
  requiredObjectOfStrings: objectOf(string).isRequired
}

PropTypes.shape

prop-types

import { number, shape, string } from "prop-types";

MyComponent.propTypes = {
  optionalObjectWithShape: shape({
    age: number,
    name: string
  }),

  requiredObjectWithShape: shape({
    age: number,
    name: string
  }).isRequired,

  requiredObjectWithRequiredShape: shape({
    age: number.isRequired,
    name: string.isRequired
  }).isRequired,
}

PropTypes.any

prop-types
import { any } from "prop-types";

MyComponent.propTypes = {
  requiredAny: any.isRequired
}

Simulate (basic)

react-addons-test-utils
var subject = TestUtils.renderIntoDocument(
  <div onClick={handleClick} />
);

TestUtils.Simulate.click(subject);

Simulate (with data)

react-addons-test-utils
function handleChange (event) {
  console.log('A change was simulated with key: ' + event.key);
}

var subject = TestUtils.renderIntoDocument(
  <input type="text" onChange={handleChange} />
);

TestUtils.Simulate.change(subject, { key: "Enter" });

renderIntoDocument

react-addons-test-utils
var componentTree = TestUtils.renderIntoDocument(<div><span /></div>);

console.log('You mounted a component tree with a ' + componentTree.tagName + ' at the root!');

mockComponent

react-addons-test-utils
// no example

isElement

react-addons-test-utils
expect(TestUtils.isElement(<div />)).toBe(true);

isElementOfType

react-addons-test-utils
var MyComponent = React.createClass({
  render () {
    return <div />;
  }
});

expect(
  TestUtils.isElementOfType(<MyComponent />, MyComponent)
).toBe(true);

isDOMComponent

react-addons-test-utils
var subject = TestUtils.renderIntoDocument(<div />);

expect(
  TestUtils.isDOMComponent(subject)
).toBe(true);

isCompositeComponent

react-addons-test-utils
var subject = TestUtils.renderIntoDocument(
  <CompositeComponent />
);

expect(
  TestUtils.isCompositeComponent(subject)
).toBe(true);

isCompositeComponentWithType

react-addons-test-utils
var CompositeComponent = React.createClass({
  render () {
    return <div />;
  }
});

var subject = TestUtils.renderIntoDocument(
  <CompositeComponent />
);

expect(
  TestUtils.isCompositeComponentWithType(
    subject,
    CompositeComponent
  )
).toBe(true);

findAllInRenderedTree

react-addons-test-utils
var CompositeComponent = React.createClass({
  render () {
    return <div><div /></div>;
  }
});

var componentTree = TestUtils.renderIntoDocument(
  <CompositeComponent />
);

var allDivs = TestUtils.findAllInRenderedTree(
  componentTree,
  (c) => c.tagName === 'DIV'
)

expect(allDivs).toBeAn('array');
expect(allDivs.length).toBe(2);

scryRenderedDOMComponentsWithClass

react-addons-test-utils
var CompositeComponent = React.createClass({
  render () {
    return (
      <div className="target">
        <div className="not-target">
          <div className="target" />
        </div>
      </div>
    );
  }
});

var componentTree = TestUtils.renderIntoDocument(
  <CompositeComponent />
);

var allDOMComponentsWithMatchingClass = TestUtils.scryRenderedDOMComponentsWithClass(
  componentTree,
  'target'
);

expect(allDOMComponentsWithMatchingClass).toBeAn('array');
expect(allDOMComponentsWithMatchingClass.length).toBe(2);

findRenderedDOMComponentWithClass

react-addons-test-utils
var MyCompositeComponent = React.createClass({
  render () {
    return <MyNestedComponent />;
  }
});

var MyNestedComponent = React.createClass({
  render () {
    return <div className="nested"/>;
  }
});

var componentTree = TestUtils.renderIntoDocument(<MyCompositeComponent />);

var singleComponentWithMatchedClass = TestUtils.findRenderedDOMComponentWithClass(
  componentTree,
  'nested'
);

expect(singleComponentWithMatchedClass).toBeAn('object');
expect(singleComponentWithMatchedClass).toNotBeAn('array');
expect(singleComponentWithMatchedClass.className).toBe('nested');

scryRenderedDOMComponentsWithTag

react-addons-test-utils
var CompositeComponent = React.createClass({
  render () {
    return <div><div /></div>;
  }
});

var componentTree = TestUtils.renderIntoDocument(
  <CompositeComponent />
);

var allDivs = TestUtils.scryRenderedDOMComponentsWithTag(
  componentTree,
  'DIV'
);

expect(allDivs).toBeAn('array');
expect(allDivs.length).toBe(2);

findRenderedDOMComponentWithTag

react-addons-test-utils
var MyCompositeComponent = React.createClass({
  render () {
    return <MyNestedComponent />;
  }
});

var MyNestedComponent = React.createClass({
  render () {
    return <div />;
  }
});

var componentTree = TestUtils.renderIntoDocument(<MyCompositeComponent />);

var onlyDiv = TestUtils.findRenderedDOMComponentWithTag(
  componentTree,
  'div'
);

expect(onlyDiv).toBeAn('object');
expect(onlyDiv).toNotBeAn('array');
expect(onlyDiv.tagName).toBe('DIV');

scryRenderedComponentsWithType

react-addons-test-utils
var MyCompositeComponent = React.createClass({
  render () {
    return (
      <div>
        <Target />
        <br />
        <Target />
      </div>
    )
  }
});

var Target = React.createClass({
  render () {
    return <div />;
  }
});

var componentTree = TestUtils.renderIntoDocument(
  <MyCompositeComponent />
);

var allTargetComponents = TestUtils.scryRenderedComponentsWithType(
  componentTree,
  Target
);

expect(allTargetComponents).toBeAn('array');
expect(allTargetComponents.length).toBe(2);

findRenderedComponentWithType

react-addons-test-utils
var MyCompositeComponent = React.createClass({
  render () { return <TargetComponent /> }
});

var TargetComponent = React.createClass({
  render () { return <div /> }
});

var componentTree = TestUtils.renderIntoDocument(
  <MyCompositeComponent />
);

var onlyTargetComponent = TestUtils.findRenderedComponentWithType(
  componentTree,
  TargetComponent
);

expect(onlyTargetComponent).toBeAn('object');
expect(onlyTargetComponent).toNotBeAn('array');
expect(TestUtils.isCompositeComponentWithType(
  onlyTargetComponent,
  TargetComponent
)).toBe(true);

Shallow rendering (basics)

react-addons-test-utils
// 1. create a renderer
var renderer = TestUtils.createRenderer();

// 2. render component into renderer
renderer.render(<MyComponent />);

// 3. capture renderer output
var subject = renderer.getRenderOutput();

// 4. make assertions
expect(subject.type).toBe('div');

Shallow rendering (type example)

react-addons-test-utils
var renderer = TestUtils.createRenderer();

renderer.render(<MyComponent />);

var subject = renderer.getRenderOutput();

expect(subject.type).toBe('div');  // => true

Shallow rendering (props example)

react-addons-test-utils
var renderer = TestUtils.createRenderer();

renderer.render(<MyComponent className="my-component" />);

var subject = renderer.getRenderOutput();

expect(subject.props.className).toBe('my-component'); // => true

Shallow rendering (child-count example)

react-addons-test-utils
var renderer = TestUtils.createRenderer();

renderer.render(
  <MyList items={[1, 2, 3]} />
);

var subject = renderer.getRenderOutput();

var childCount = React.Children.count(subject.props.children);

expect(childCount).toBe(3); // => true

Shallow rendering (child-equality example)

react-addons-test-utils
var renderer = TestUtils.createRenderer();

renderer.render(
  <MyComponent>
    <div>Thing 1</div>
    <div>Thing 2</div>
  </MyComponent>
);

var subject = renderer.getRenderOutput();

expect(subject.props.children).toEqual([
  <div>Thing 1</div>,
  <div>Thing 2</div>
]); // => true

Shallow rendering (events example)

react-addons-test-utils
var renderer = TestUtils.createRenderer();

var spy = expect.createSpy();

renderer.render(<MyComponent onClick={spy} />);

var subject = renderer.getRenderOutput();

expect(spy.call.length).toEqual(1); // => true

Shallow rendering (state changes example)

react-addons-test-utils
var renderer = TestUtils.createRenderer();

renderer.render(<ClickCounter />);

// test initial rendering
var result = renderer.getRenderOutput();

expect(result.props.children).toEqual(0);


// test post-click rendering
result.props.onClick();

var clickedResult = renderer.getRenderOutput();

expect(clickedResult.props.children).toEqual(1);

ref (class component)

class AutoFocusTextInput extends React.Component {
  componentDidMount() {
    this.textInput.focus();
  }

  render() {
    return (
      <CustomTextInput
        ref={(input) => { this.textInput = input; }} />
    );
  }
}

ref (functional component)

function CustomTextInput(props) {
  let textInput = null;

  function handleClick() {
    textInput.focus();
  }

  return (
    <div>
      <input
        type="text"
        ref={(input) => { textInput = input; }} />
      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  );
}

functional component

react
const Greeting = props => <div>Hello {props.name}</div>;

functional component (with context)

react
import { string } from "prop-types";

const Greeting = (props, context) => (
  <div>{context.salutation} {props.name}</div>
);

Greeting.contextTypes = { salutation: string };