githubEdit

React.js

Components

Components

import React from 'react'
import ReactDOM from 'react-dom'
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

import React, {Component} from 'react'
import ReactDOM from 'react-dom'
class Hello extends Component {

Properties

{: .-setup}

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

See: Propertiesarrow-up-right

States

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.

Nest components to separate concerns.

See: Composing Componentsarrow-up-right

Children

{: data-line="2"}

Children are passed as the children property.

Defaults

Setting default props

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.

See: Setting the default statearrow-up-right

Other components

{: .-three-column}

Functional components

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

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

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

Hooks are a new addition in React 16.8.

See: Hooks at a Glancearrow-up-right

Declaring multiple state variables

Effect hook

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

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

Use FriendStatus

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

References

Allows access to DOM nodes.

See: Refs and the DOMarrow-up-right

DOM Events

Pass functions to attributes like onChange.

See: Eventsarrow-up-right

Other features

Transferring props

{: .-setup}

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

Style shorthand

See: Inline stylesarrow-up-right

Inner HTML

See: Dangerously set innerHTMLarrow-up-right

Lists

Always supply a key property.

Conditionals

Short-circuit evaluation

New features

Returning multiple elements

You can return multiple elements as arrays or fragments.

Arrays

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

Fragments

See: Fragments and stringsarrow-up-right

Returning strings

You can return just a string.

See: Fragments and stringsarrow-up-right

Errors

Catch errors via componentDidCatch. (React 16+)

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

Portals

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

See: Portalsarrow-up-right

Hydration

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

PropTypes

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