cheatsheets/react.md

9.3 KiB

title category layout
React.js React 2017/sheet

{%raw%}

Getting started

{:.-three-column}

Getting started

class MyComponent extends React.Component {
  render () {
    return <div className='message-box'>
      Hello {this.props.name}
    </div>
  }
}
const el = document.body
ReactDOM.render(<MyComponent name='John' />, el)

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

Functional components

function MyComponent ({ name }) {
  return <div className='message-box'>
    Hello {name}
  </div>
}

Nesting

class Info extends React.Component {
  render () {
    const { avatar, username } = this.props

    return <div>
      <UserAvatar src={avatar} />
      <UserProfile username={username} />
    </div>
  }
}

Nest components to separate concerns. See: multiple components

Component API

this.forceUpdate()
this.isMounted()

this.setState({ ... })
this.replaceState({ ... })

this.state
this.props

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

Component specs

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

Methods and properties you can override. See component specs.

States & properties

<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

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

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

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

Lifecycle

{:.-two-column}

Mounting

| componentWillMount() | Before rendering (no DOM yet) | | componentDidMount() | After rendering | | componentWillUnmount() | Invoked before DOM removal |

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

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

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.

DOM nodes

{:.-two-column}

References

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

Allows access to DOM nodes. See References.

DOM Events

<input type="text"
    value={this.state.value}
    onChange={this.handleChange} />

{:.light}

handleChange: function(event) {
  this.setState({ value: event.target.value });
}

Add attributes like onChange. See events.

Property validation

React.PropTypes

PropType Description
any Anything
--- ---
string
number
func Function
bool True or false
--- ---
oneOf(any) Enum types
oneOfType(type array) Union
--- ---
array
arrayOf(...)
--- ---
object
objectOf(...)
instanceOf(...)
shape(...)
--- ---
element React element
node DOM node
--- ---
.isRequired Required

See propTypes.

Basic types

MyComponent.propTypes = {
  email:      React.PropTypes.string,
  seats:      React.PropTypes.number,
  callback:   React.PropTypes.func,
  isClosed:   React.PropTypes.bool,
  any:        React.PropTypes.any
}

See propTypes.

Required types

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

Add .isRequired.

React elements

MyComponent.propTypes = {
  // React element
  element:  React.PropTypes.element,

  // num, string, element, or an array of those
  node:     React.PropTypes.node
}

Use .element, .node.

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

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

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

Supply your own function.

Other features

Propagating properties

<VideoPlayer src="video.mp4" />
class VideoPlayer extends React.Component {
  render () {
    return <VideoEmbed {...this.props} />
  }
}

Propagates src="..." down to the sub-component.

See Transferring props.

Top-level API

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+

JSX patterns

Style shorthand

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

See inline styles.

Inner HTML

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

See dangerously set innerHTML.

Lists

var TodoList = React.createClass({
  render: function() {
    function item(itemText) {
      return <li>{itemText}</li>;
    };
    return <ul>{this.props.items.map(item)}</ul>;
  }
});

See also

{:.-two-column}

Also see

{%endraw%}