githubEdit

React.js

Components

{: .-three-column}

Components

{: .-prime}

import React from 'react'
import ReactDOM from 'react-dom'

{: .-setup}

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

Use the React.js jsfiddlearrow-up-right to start hacking. (or the unofficial jsbinarrow-up-right)

Import multiple exports

{: .-prime}

{: .-setup}

Properties

{: .-setup}

{: data-line="2,3"}

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

See: Propertiesarrow-up-right

States

{: data-line="2,3"}

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

With Babelarrow-up-right you can use proposal-class-fieldsarrow-up-right and get rid of constructor

See: Statesarrow-up-right

Nesting

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

{: data-line="5,6,7,8,9,10"}

Nest components to separate concerns.

See: Composing Componentsarrow-up-right

Children

{: data-line="2"}

{: data-line="4"}

Children are passed as the children property.

Defaults

Setting default props

{: data-line="1"}

See: defaultPropsarrow-up-right

Setting default state

{: data-line="4"}

Set the default state in the constructor().

And without constructor using Babelarrow-up-right with proposal-class-fieldsarrow-up-right.

{: data-line="2"}

See: Setting the default statearrow-up-right

Other components

{: .-three-column}

Functional components

{: data-line="1"}

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

See: Function and Class Componentsarrow-up-right

Pure components

{: data-line="3"}

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

See: Pure componentsarrow-up-right

Component API

These methods and properties are available for Component instances.

See: Component APIarrow-up-right

Lifecycle

{: .-two-column}

Mounting

Method
Description

constructor (props)

Before rendering #arrow-up-right

componentWillMount()

Don't use this #arrow-up-right

render()

componentDidMount()

After rendering (DOM available) #arrow-up-right

---

---

componentWillUnmount()

Before DOM removal #arrow-up-right

---

---

componentDidCatch()

Catch errors (16+) #arrow-up-right

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

Updating

Method
Description

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 specsarrow-up-right

Hooks (New)

{: .-two-column}

State Hook

{: data-line="5,10"}

Hooks are a new addition in React 16.8.

See: Hooks at a Glancearrow-up-right

Declaring multiple state variables

Effect hook

{: data-line="6,7,8,9,10"}

If you're familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

By default, React runs the effects after every render — including the first render.

Building your own hooks

Define FriendStatus

{: data-line="11,12,13,14"}

Effects may also optionally specify how to "clean up” after them by returning a function.

Use FriendStatus

{: data-line="2"}

See: Building Your Own Hooksarrow-up-right

Hooks API Reference

Also see: Hooks FAQarrow-up-right

Basic Hooks

Hook
Description

useState(initialState)

useEffect(() => { ... })

useContext(MyContext)

value returned from React.createContext

Full details: Basic Hooksarrow-up-right

Additional Hooks

Hook
Description

useReducer(reducer, initialArg, init)

useCallback(() => { ... })

useMemo(() => { ... })

useRef(initialValue)

useImperativeHandle(ref, () => { ... })

useLayoutEffect

identical to useEffect, but it fires synchronously after all DOM mutations

useDebugValue(value)

display a label for custom hooks in React DevTools

Full details: Additional Hooksarrow-up-right

DOM nodes

{: .-two-column}

References

{: data-line="4,9"}

Allows access to DOM nodes.

See: Refs and the DOMarrow-up-right

DOM Events

{: data-line="5,9"}

Pass functions to attributes like onChange.

See: Eventsarrow-up-right

Other features

Transferring props

{: .-setup}

{: data-line="3"}

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

See Transferring propsarrow-up-right

Top-level API

There are more, but these are most common.

See: React top-level APIarrow-up-right

JSX patterns

{: .-two-column}

Style shorthand

See: Inline stylesarrow-up-right

Inner HTML

See: Dangerously set innerHTMLarrow-up-right

Lists

{: data-line="6,7"}

Always supply a key property.

Conditionals

Short-circuit evaluation

New features

{: .-three-column}

Returning multiple elements

You can return multiple elements as arrays or fragments.

Arrays

{: data-line="3,4,5,6"}

Fragments

{: data-line="3,4,5,6,7,8"}

See: Fragments and stringsarrow-up-right

Returning strings

{: data-line="2"}

You can return just a string.

See: Fragments and stringsarrow-up-right

Errors

{: data-line="3,4,5"}

Catch errors via componentDidCatch. (React 16+)

See: Error handling in React 16arrow-up-right

Portals

{: data-line="2,3,4,5"}

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

See: Portalsarrow-up-right

Hydration

{: data-line="2"}

Use ReactDOM.hydrate instead of using ReactDOM.render if you're rendering over the output of ReactDOMServerarrow-up-right.

See: Hydratearrow-up-right

Property validation

{: .-three-column}

PropTypes

{: .-setup}

See: Typechecking with PropTypesarrow-up-right

| any | Anything |

Basic

| string | | | number | | | func | Function | | bool | True 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

| element | React element | | node | DOM node |

Required

| (···).isRequired | Required |

Basic types

Required types

Elements

Enumerables (oneOf)

Arrays and objects

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

Custom validation

Also see

Last updated