Posts

React.js cheatsheet

React is a JavaScript library for building user interfaces. These guide targets React v15 to v16

#Components

Components

<span class="token keyword">import</span> React <span class="token keyword">from</span> <span class="token string">'react'</span>
<span class="token keyword">import</span> ReactDOM <span class="token keyword">from</span> <span class="token string">'react-dom'</span>
<span class="token keyword">class</span> <span class="token class-name">Hello</span> <span class="token keyword">extends</span> <span class="token class-name">React<span class="token punctuation">.</span>Component</span> <span class="token punctuation">{</span>
  render <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>div</span> <span class="token attr-name">className</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">'</span>message-box<span class="token punctuation">'</span></span><span class="token punctuation">></span></span>
      Hello <span class="token punctuation">{</span><span class="token keyword">this</span><span class="token punctuation">.</span>props<span class="token punctuation">.</span>name<span class="token punctuation">}</span>
    <span class="token tag"><span class="token tag"><span class="token punctuation"></</span>div</span><span class="token punctuation">></span></span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">const</span> el <span class="token operator">=</span> document<span class="token punctuation">.</span>body
ReactDOM<span class="token punctuation">.</span><span class="token function">render</span><span class="token punctuation">(</span><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Hello</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">'</span>John<span class="token punctuation">'</span></span> <span class="token punctuation">/></span></span><span class="token punctuation">,</span> el<span class="token punctuation">)</span>

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

Import multiple exports

<span class="token keyword">import</span> React<span class="token punctuation">,</span> <span class="token punctuation">{</span>Component<span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'react'</span>
<span class="token keyword">import</span> ReactDOM <span class="token keyword">from</span> <span class="token string">'react-dom'</span>
<span class="token keyword">class</span> <span class="token class-name">Hello</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span>
  <span class="token operator">...</span>
<span class="token punctuation">}</span>

Properties

<span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Video</span> <span class="token attr-name">fullscreen</span><span class="token attr-value"><span class="token punctuation">=</span>{true}</span> <span class="token attr-name">autoplay</span><span class="token attr-value"><span class="token punctuation">=</span>{false}</span> <span class="token punctuation">/></span></span>
render () {
  this.props.fullscreen
  const { fullscreen, autoplay } = this.props
  ···
}
 
 

Use this.props to access properties passed to the component.

See: Properties

States

<span class="token function">constructor</span><span class="token punctuation">(</span>props<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">super</span><span class="token punctuation">(</span>props<span class="token punctuation">)</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>state <span class="token operator">=</span> <span class="token punctuation">{</span> username<span class="token punctuation">:</span> undefined <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">setState</span><span class="token punctuation">(</span><span class="token punctuation">{</span> username<span class="token punctuation">:</span> <span class="token string">'rstacruz'</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
render () {
  this.state.username
  const { username } = this.state
  ···
}
 
 

Use states (this.state) to manage dynamic data.

With Babel you can use proposal-class-fields and get rid of constructor

<span class="token keyword">class</span> <span class="token class-name">Hello</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span>
  state <span class="token operator">=</span> <span class="token punctuation">{</span> username<span class="token punctuation">:</span> undefined <span class="token punctuation">}</span><span class="token punctuation">;</span>
  <span class="token operator">...</span>
<span class="token punctuation">}</span>

See: States

Nesting

<span class="token keyword">class</span> <span class="token class-name">Info</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span>
  render <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> <span class="token punctuation">{</span> avatar<span class="token punctuation">,</span> username <span class="token punctuation">}</span> <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>props

    <span class="token keyword">return</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>div</span><span class="token punctuation">></span></span>
      <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>UserAvatar</span> <span class="token attr-name">src</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span>avatar<span class="token punctuation">}</span></span> <span class="token punctuation">/></span></span>
      <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>UserProfile</span> <span class="token attr-name">username</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span>username<span class="token punctuation">}</span></span> <span class="token punctuation">/></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation"></</span>div</span><span class="token punctuation">></span></span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

As of React v16.2.0, fragments can be used to return multiple children without adding extra wrapping nodes to the DOM.

<span class="token keyword">import</span> React<span class="token punctuation">,</span> <span class="token punctuation">{</span>
  Component<span class="token punctuation">,</span>
  Fragment
<span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'react'</span>

<span class="token keyword">class</span> <span class="token class-name">Info</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span>
  render <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> <span class="token punctuation">{</span> avatar<span class="token punctuation">,</span> username <span class="token punctuation">}</span> <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>props

    <span class="token keyword">return</span> <span class="token punctuation">(</span>
      <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Fragment</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>UserAvatar</span> <span class="token attr-name">src</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span>avatar<span class="token punctuation">}</span></span> <span class="token punctuation">/></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>UserProfile</span> <span class="token attr-name">username</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span>username<span class="token punctuation">}</span></span> <span class="token punctuation">/></span></span>
      <span class="token tag"><span class="token tag"><span class="token punctuation"></</span>Fragment</span><span class="token punctuation">></span></span>
    <span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

Nest components to separate concerns.

See: Composing Components

Children

<AlertBox>
  <h1>You have pending notifications</h1>
</AlertBox>
 
class AlertBox extends Component {
  render () {
    return <div className='alert-box'>
      {this.props.children}
    </div>
  }
}
 

Children are passed as the children property.

#Defaults

Setting default props

Hello.defaultProps = {
  color: 'blue'
}
 

See: defaultProps

Setting default state

class Hello extends Component {
  constructor (props) {
    super(props)
    this.state = { visible: true }
  }
}
 

Set the default state in the constructor().

And without constructor using Babel with proposal-class-fields.

<span class="token keyword">class</span> <span class="token class-name">Hello</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span>
    state <span class="token operator">=</span> <span class="token punctuation">{</span> visible<span class="token punctuation">:</span> <span class="token boolean">true</span> <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

See: Setting the default state

#Other components

Functional components

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

Functional components have no state. Also, their props are passed as the first parameter to a function.

See: Function and Class Components

Pure components

import React, {PureComponent} from 'react'

class MessageBox extends PureComponent {
  ···
}
 

Performance-optimized version of React.Component. Doesn’t rerender if props/state hasn’t changed.

See: Pure components

Component API

<span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">forceUpdate</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">setState</span><span class="token punctuation">(</span><span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">setState</span><span class="token punctuation">(</span>state <span class="token operator">=></span> <span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">this</span><span class="token punctuation">.</span>state
<span class="token keyword">this</span><span class="token punctuation">.</span>props

These methods and properties are available for Component instances.

See: Component API

#Lifecycle

Mounting

MethodDescription
constructor (props)Before rendering #
componentWillMount()Don’t use this #
render()Render #
componentDidMount()After rendering (DOM available) #
componentWillUnmount()Before DOM removal #
componentDidCatch()Catch errors (16+) #

Set initial the state on constructor(). Add DOM event handlers, timers (etc) on componentDidMount(), then remove them on componentWillUnmount().

Updating

MethodDescription
componentDidUpdate (prevProps, prevState, snapshot)Use setState() here, but remember to compare props
shouldComponentUpdate (newProps, newState)Skips render() if returns false
render()Render
componentDidUpdate (prevProps, prevState)Operate on the DOM here

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

See: Component specs

#DOM nodes

References

class MyComponent extends Component {
  render () {
    return <div>
      <input ref={el => this.input = el} />
    </div>
  }

  componentDidMount () {
    this.input.focus()
  }
}
 
 

Allows access to DOM nodes.

See: Refs and the DOM

DOM Events

class MyComponent extends Component {
  render () {
    <input type="text"
        value={this.state.value}
        onChange={event => this.onChange(event)} />
  }

  onChange (event) {
    this.setState({ value: event.target.value })
  }
}
 
 

Pass functions to attributes like onChange.

See: Events

#Other features

Transferring props

<span class="token tag"><span class="token tag"><span class="token punctuation"><</span>VideoPlayer</span> <span class="token attr-name">src</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>video.mp4<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
class VideoPlayer extends Component {
  render () {
    return <VideoEmbed {...this.props} />
  }
}
 

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

See Transferring props

Top-level API

React<span class="token punctuation">.</span><span class="token function">createClass</span><span class="token punctuation">(</span><span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
React<span class="token punctuation">.</span><span class="token function">isValidElement</span><span class="token punctuation">(</span>c<span class="token punctuation">)</span>
ReactDOM<span class="token punctuation">.</span><span class="token function">render</span><span class="token punctuation">(</span><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Component</span> <span class="token punctuation">/></span></span><span class="token punctuation">,</span> domnode<span class="token punctuation">,</span> <span class="token punctuation">[</span>callback<span class="token punctuation">]</span><span class="token punctuation">)</span>
ReactDOM<span class="token punctuation">.</span><span class="token function">unmountComponentAtNode</span><span class="token punctuation">(</span>domnode<span class="token punctuation">)</span>
ReactDOMServer<span class="token punctuation">.</span><span class="token function">renderToString</span><span class="token punctuation">(</span><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Component</span> <span class="token punctuation">/></span></span><span class="token punctuation">)</span>
ReactDOMServer<span class="token punctuation">.</span><span class="token function">renderToStaticMarkup</span><span class="token punctuation">(</span><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Component</span> <span class="token punctuation">/></span></span><span class="token punctuation">)</span>

There are more, but these are most common.

See: React top-level API

#JSX patterns

Style shorthand

<span class="token keyword">const</span> style <span class="token operator">=</span> <span class="token punctuation">{</span> height<span class="token punctuation">:</span> <span class="token number">10</span> <span class="token punctuation">}</span>
<span class="token keyword">return</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>div</span> <span class="token attr-name">style</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span>style<span class="token punctuation">}</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation"></</span>div</span><span class="token punctuation">></span></span>
<span class="token keyword">return</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>div</span> <span class="token attr-name">style</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span><span class="token punctuation">{</span> margin<span class="token punctuation">:</span> <span class="token number">0</span><span class="token punctuation">,</span> padding<span class="token punctuation">:</span> <span class="token number">0</span> <span class="token punctuation">}</span><span class="token punctuation">}</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation"></</span>div</span><span class="token punctuation">></span></span>

See: Inline styles

Inner HTML

<span class="token keyword">function</span> <span class="token function">markdownify</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token keyword">return</span> <span class="token string">"<p>...</p>"</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
<span class="token tag"><span class="token tag"><span class="token punctuation"><</span>div</span> <span class="token attr-name">dangerouslySetInnerHTML</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span><span class="token punctuation">{</span>__html<span class="token punctuation">:</span> <span class="token function">markdownify</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">}</span><span class="token punctuation">}</span></span> <span class="token punctuation">/></span></span>

See: Dangerously set innerHTML

Lists

class TodoList extends Component {
  render () {
    const { items } = this.props

    return <ul>
      {items.map(item =>
        <TodoItem item={item} key={item.key} />)}
    </ul>
  }
}
 
 

Always supply a key property.

Conditionals

<span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Fragment</span><span class="token punctuation">></span></span>
  <span class="token punctuation">{</span>showMyComponent
    <span class="token operator">?</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>MyComponent</span> <span class="token punctuation">/></span></span>
    <span class="token punctuation">:</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>OtherComponent</span> <span class="token punctuation">/></span></span><span class="token punctuation">}</span>
<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>Fragment</span><span class="token punctuation">></span></span>

Short-circuit evaluation

<span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Fragment</span><span class="token punctuation">></span></span>
  <span class="token punctuation">{</span>showPopup <span class="token operator">&&</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Popup</span> <span class="token punctuation">/></span></span><span class="token punctuation">}</span>
  <span class="token operator">...</span>
<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>Fragment</span><span class="token punctuation">></span></span>

#New features

Returning multiple elements

You can return multiple elements as arrays or fragments.

Arrays

render () {
  // Don't forget the keys!
  return [
    <li key="A">First item</li>,
    <li key="B">Second item</li>
  ]
}
 
 
 
 

Fragments

render () {
  // Fragments don't require keys!
  return (
    <Fragment>
      <li>First item</li>
      <li>Second item</li>
    </Fragment>
  )
}
 
 
 
 
 
 

See: Fragments and strings

Returning strings

render() {
  return 'Look ma, no spans!';
}
 

You can return just a string.

See: Fragments and strings

Errors

class MyComponent extends Component {
  ···
  componentDidCatch (error, info) {
    this.setState({ error })
  }
}
 
 
 

Catch errors via componentDidCatch. (React 16+)

See: Error handling in React 16

Portals

render () {
  return React.createPortal(
    this.props.children,
    document.getElementById('menu')
  )
}
 
 
 
 

This renders this.props.children into any location in the DOM.

See: Portals

Hydration

const el = document.getElementById('app')
ReactDOM.hydrate(<App />, el)
 

Use ReactDOM.hydrate instead of using ReactDOM.render if you’re rendering over the output of ReactDOMServer.

See: Hydrate

#Property validation

PropTypes

<span class="token keyword">import</span> PropTypes <span class="token keyword">from</span> <span class="token string">'prop-types'</span>

See: Typechecking with PropTypes

anyAnything

Basic

string 
number 
funcFunction
boolTrue or false

Enum

oneOf(any)Enum types
oneOfType(type array)Union

Array

array 
arrayOf(…) 

Object

object 
objectOf(…)Object with values of a certain type
instanceOf(…)Instance of a class
shape(…) 

Elements

elementReact element
nodeDOM node

Required

(···).isRequiredRequired

Basic types

MyComponent<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  email<span class="token punctuation">:</span>      PropTypes<span class="token punctuation">.</span>string<span class="token punctuation">,</span>
  seats<span class="token punctuation">:</span>      PropTypes<span class="token punctuation">.</span>number<span class="token punctuation">,</span>
  callback<span class="token punctuation">:</span>   PropTypes<span class="token punctuation">.</span>func<span class="token punctuation">,</span>
  isClosed<span class="token punctuation">:</span>   PropTypes<span class="token punctuation">.</span>bool<span class="token punctuation">,</span>
  any<span class="token punctuation">:</span>        PropTypes<span class="token punctuation">.</span>any
<span class="token punctuation">}</span>

Required types

MyCo<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  name<span class="token punctuation">:</span>  PropTypes<span class="token punctuation">.</span>string<span class="token punctuation">.</span>isRequired
<span class="token punctuation">}</span>

Elements

MyCo<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  <span class="token comment" spellcheck="true">// React element</span>
  element<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span>element<span class="token punctuation">,</span>

  <span class="token comment" spellcheck="true">// num, string, element, or an array of those</span>
  node<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span>node
<span class="token punctuation">}</span>

Enumerables (oneOf)

MyCo<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  direction<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span><span class="token function">oneOf</span><span class="token punctuation">(</span><span class="token punctuation">[</span>
    <span class="token string">'left'</span><span class="token punctuation">,</span> <span class="token string">'right'</span>
  <span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

Arrays and objects

MyCo<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  list<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span>array<span class="token punctuation">,</span>
  ages<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span><span class="token function">arrayOf</span><span class="token punctuation">(</span>PropTypes<span class="token punctuation">.</span>number<span class="token punctuation">)</span><span class="token punctuation">,</span>
  user<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span>object<span class="token punctuation">,</span>
  user<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span><span class="token function">objectOf</span><span class="token punctuation">(</span>PropTypes<span class="token punctuation">.</span>number<span class="token punctuation">)</span><span class="token punctuation">,</span>
  message<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span><span class="token function">instanceOf</span><span class="token punctuation">(</span>Message<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
MyCo<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  user<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span><span class="token function">shape</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    name<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span>string<span class="token punctuation">,</span>
    age<span class="token punctuation">:</span>  PropTypes<span class="token punctuation">.</span>number
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

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

Custom validation

MyCo<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  customProp<span class="token punctuation">:</span> <span class="token punctuation">(</span>props<span class="token punctuation">,</span> key<span class="token punctuation">,</span> componentName<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token regex">/matchme/</span><span class="token punctuation">.</span><span class="token function">test</span><span class="token punctuation">(</span>props<span class="token punctuation">[</span>key<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Error</span><span class="token punctuation">(</span><span class="token string">'Validation failed!'</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

#Also see