React.js (v0.14)

Deprecated: this guide targets an old version of React (v0.14). See the updated React cheatsheet for new versions.

A cheatsheet by @rstacruz|Refreshed 5 months ago.Refresh|View source on Github

{%raw%}

Components

Components

var Component = React.createClass({
  render: function () {
    return <div>Hello {this.props.name}</div>;
  }
});
ReactDOM.render(<Component name="John" />, document.body);

Use the React.js jsfiddle to start hacking. (or the unofficial jsbin)

Nesting

Nesting

var UserAvatar  = React.createClass({...});
var UserProfile = React.createClass({...});
var Info = React.createClass({
  render() {
    return <div>
      <UserAvatar src={this.props.avatar} />
      <UserProfile username={this.props.username} />
    </div>;
  }
});

Nest components to separate concerns. See multiple components.

States and props

States and props

<MyComponent fullscreen={true} />
// props
  this.props.fullscreen //=> true

// state
  this.setState({ username: 'rstacruz' });
  this.replaceState({ ... });
  this.state.username //=> 'rstacruz'
render: function () {
  return <div className={this.props.fullscreen ? 'full' : ''}>
    Welcome, {this.state.username}
  </div>;
}

Use props (this.props) to access parameters passed from the parent.
Use states (this.state) to manage dynamic data.

Setting defaults

Setting defaults

React.createClass({
  getInitialState: function () {
    return { comments: [] };
  },

  getDefaultProps: function () {
    return { name: "Hello" };
  }
);

Pre-populates this.state.comments and this.props.name.

Component API

Component API

ReactDOM.findDOMNode(c)  // 0.14+
React.findDOMNode(c)  // 0.13
c.getDOMNode()        // 0.12 below
c.forceUpdate()
c.isMounted()

c.state
c.props

c.setState({ ... })
c.replaceState({ ... })

c.setProps({ ... })       // for deprecation
c.replaceProps({ ... })   // for deprecation

c.refs

These are methods available for Component instances. See Component API.

Component specs

Component specs

Method What
render()  
getInitialState()  
getDefaultProps()  
mixins: [ ... ] Mixins … more
propTypes: { ... } Validation … more
statics: { ... } Static methods
displayName: "..." Automatically filled by JSX

Methods and properties you can override. See component specs.

Mounting

Mounting

componentWillMount() Before rendering (no DOM yet)
componentDidMount() After rendering

Before initial rendering occurs. Add your DOM stuff on didMount (events, timers, etc). See reference.

Updating

Updating

componentWillReceiveProps(newProps={}) Use setState() here
shouldComponentUpdate(newProps={}, newState={}) Skips render() if returns false
componentWillUpdate(newProps={}, newState={}) Can’t use setState() here
componentDidUpdate(prevProps={}, prevState={}) Operate on the DOM here

Called when parents change properties and .setState(). These are not called for initial renders. See reference.

Unmounting

Unmounting

componentWillUnmount() Invoked before DOM removal

Clear your DOM stuff here (probably done on didMount). See reference.

Example: loading data

Example: loading data

React.createClass({
  componentDidMount: function () {
    $.get(this.props.url, function (data) {
      this.setState(data);
    }.bind(this));
  },

  render: function () {
    return <CommentList data={this.state.data} />
  }
});

See initial AJAX data.

References

References

<input ref="myInput">
this.refs.myInput
ReactDOM.findDOMNode(this.refs.myInput).focus()
ReactDOM.findDOMNode(this.refs.myInput).value

DOM Events

DOM Events

Add attributes like onChange. See events.

<input type="text"
    value={this.state.value}
    onChange={this.handleChange} />
handleChange: function(event) {
  this.setState({ value: event.target.value });
}

Allows access to DOM nodes. See References.

Two-way binding

Two-way binding

Email: <input type="text" valueLink={this.linkState('email')} />
React.createClass({
  mixins: [React.addons.LinkedStateMixin]
});
this.state.email

Use LinkedStateMixin for easier two-way binding.

Basic types

Basic types

React.createClass({
  propTypes: {
    email:      React.PropTypes.string,
    seats:      React.PropTypes.number,
    settings:   React.PropTypes.object,
    callback:   React.PropTypes.func,
    isClosed:   React.PropTypes.bool,
    any:        React.PropTypes.any,
  }
});

Primitive types: .string, .number, .func, and .bool. See propTypes.

Required types

Required types

propTypes: {
  requiredFunc:  React.PropTypes.func.isRequired,
  requiredAny:   React.PropTypes.any.isRequired,

Add .isRequired.

React elements

React elements

propTypes: {
  element:  React.PropTypes.element,  // react element
  node:     React.PropTypes.node,     // num, string, element
                                      // ...or array of those

Use .element, .node.

Enumerables

Enumerables

propTypes: {
  enum:     React.PropTypes.oneOf(['M','F']),  // enum
  union:    React.PropTypes.oneOfType([        // any
              React.PropTypes.string,
              React.PropTypes.number ]),

Use .oneOf, .oneOfType.

Arrays and objects

Arrays and objects

propTypes: {
  array:    React.PropTypes.array,
  arrayOf:  React.PropTypes.arrayOf(React.PropTypes.number),
  object:   React.PropTypes.object,
  objectOf: React.PropTypes.objectOf(React.PropTypes.number),

  message:  React.PropTypes.instanceOf(Message),

  object2:  React.PropTypes.shape({
    color:  React.PropTypes.string,
    size:   React.PropTypes.number
  }),

Use .array[Of], .object[Of], .instanceOf, .shape.

Custom validation

Custom validation

propTypes: {
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error('Validation failed!');
    }
  }
}

Supply your own function.

Class set

Class set

var cx = require('classnames');

render: function() {
  var classes = cx({
    'message': true,
    'message-important': this.props.isImportant,
    'message-read': this.props.isRead
  });

  return <div className={classes}>Great Scott!</div>;
}

Manipulate DOM classes with classnames, previously known as React.addons.classSet. See Class set.

Propagating properties

Propagating properties

<VideoPlayer src="video.mp4" />
var VideoPlayer = React.createClass({
  render: function() {
    /* propagates src="..." down to this sub component */
    return <VideoEmbed {...this.props} controls='false' />;
  }
});

See Transferring props.

Mixins

Mixins

var SetIntervalMixin = {
  componentWillMount: function() { .. }
}
var TickTock = React.createClass({
  mixins: [SetIntervalMixin]
}

See addons for some built-in mixins.

React.createClass({ ... })

React.isValidElement(c)

ReactDOM.findDOMNode(c) // 0.14+
ReactDOM.render(<Component />, domnode, [callback]) // 0.14+
ReactDOM.unmountComponentAtNode(domnode) // 0.14+

ReactDOMServer.renderToString(<Component />) // 0.14+
ReactDOMServer.renderToStaticMarkup(<Component />) // 0.14+

Style shorthand

Style shorthand

var style = { backgroundImage: 'url(x.jpg)', height: 10 };
return <div style={style}></div>;

See inline styles.

InnerHTML

InnerHTML

function markdownify() { return "<p>...</p>"; }
<div dangerouslySetInnerHTML={{__html: markdownify()}} />

See dangerously set innerHTML.

Lists

Lists

var TodoList = React.createClass({
  render: function() {
    function item(itemText) {
      return <li>{itemText}</li>;
    };
    return <ul>{this.props.items.map(item)}</ul>;
  }
});
This cheat sheet can be found in the following categories: