cheatsheets/react.md

850 lines
19 KiB
Markdown
Raw Permalink Normal View History

2014-03-22 04:03:13 +00:00
---
title: React.js
2015-11-24 05:09:17 +00:00
category: React
2017-08-25 06:32:11 +00:00
ads: true
2017-08-28 15:14:30 +00:00
tags: [Featured]
2020-07-05 11:11:36 +00:00
updated: 2020-07-05
2017-08-29 16:38:47 +00:00
weight: -10
2017-10-15 18:02:23 +00:00
keywords:
- React.Component
- render()
- componentDidMount()
- props/state
- dangerouslySetInnerHTML
2017-09-27 00:19:37 +00:00
intro: |
2017-10-10 15:47:03 +00:00
[React](https://reactjs.org/) is a JavaScript library for building user interfaces. This guide targets React v15 to v16.
2014-03-22 04:03:13 +00:00
---
2015-04-17 11:01:44 +00:00
{%raw%}
2017-08-24 10:40:09 +00:00
Components
----------
{: .-three-column}
2014-03-22 04:03:13 +00:00
2017-08-24 10:40:09 +00:00
### Components
{: .-prime}
2017-08-23 22:22:00 +00:00
2017-08-24 07:13:27 +00:00
```jsx
import React from 'react'
import ReactDOM from 'react-dom'
```
2017-08-25 08:10:51 +00:00
{: .-setup}
2017-08-24 07:13:27 +00:00
2017-08-24 03:57:09 +00:00
```jsx
class Hello extends React.Component {
render () {
return <div className='message-box'>
Hello {this.props.name}
</div>
}
}
```
```jsx
const el = document.body
ReactDOM.render(<Hello name='John' />, el)
```
2017-08-24 10:40:09 +00:00
Use the [React.js jsfiddle](http://jsfiddle.net/reactjs/69z2wepo/) to start hacking. (or the unofficial [jsbin](http://jsbin.com/yafixat/edit?js,output))
2017-08-24 03:57:09 +00:00
### Import multiple exports
{: .-prime}
```jsx
import React, {Component} from 'react'
import ReactDOM from 'react-dom'
```
{: .-setup}
```jsx
class Hello extends Component {
...
}
```
2017-08-24 10:40:09 +00:00
### Properties
2017-08-24 03:57:09 +00:00
2017-08-24 10:40:09 +00:00
```html
<Video fullscreen={true} autoplay={false} />
2017-08-24 10:40:09 +00:00
```
2017-08-25 08:10:51 +00:00
{: .-setup}
2017-08-23 22:22:00 +00:00
2017-08-24 10:40:09 +00:00
```jsx
render () {
this.props.fullscreen
const { fullscreen, autoplay } = this.props
2017-08-24 10:40:09 +00:00
···
}
```
{: data-line="2,3"}
2017-08-24 03:57:09 +00:00
2017-08-24 10:40:09 +00:00
Use `this.props` to access properties passed to the component.
2017-09-15 09:53:17 +00:00
2017-10-10 15:15:42 +00:00
See: [Properties](https://reactjs.org/docs/tutorial.html#using-props)
2017-08-24 03:57:09 +00:00
2017-08-24 10:40:09 +00:00
### States
2017-08-23 22:22:00 +00:00
2017-12-07 21:35:08 +00:00
```jsx
constructor(props) {
super(props)
this.state = { username: undefined }
2017-12-07 21:35:08 +00:00
}
```
2017-08-23 22:22:00 +00:00
```jsx
2017-08-24 10:40:09 +00:00
this.setState({ username: 'rstacruz' })
2015-02-26 07:08:18 +00:00
```
2014-03-22 04:03:13 +00:00
2017-08-23 22:22:00 +00:00
```jsx
2017-08-24 10:40:09 +00:00
render () {
this.state.username
const { username } = this.state
2017-08-24 10:40:09 +00:00
···
}
2015-02-26 07:08:18 +00:00
```
{: data-line="2,3"}
2014-03-22 04:03:13 +00:00
2017-08-24 10:40:09 +00:00
Use states (`this.state`) to manage dynamic data.
2017-09-15 09:53:17 +00:00
With [Babel](https://babeljs.io/) you can use [proposal-class-fields](https://github.com/tc39/proposal-class-fields) and get rid of constructor
```jsx
class Hello extends Component {
state = { username: undefined };
...
}
```
2017-10-10 15:15:42 +00:00
See: [States](https://reactjs.org/docs/tutorial.html#reactive-state)
2017-08-24 10:40:09 +00:00
2017-08-23 22:22:00 +00:00
### Nesting
```jsx
class Info extends Component {
2017-08-23 22:22:00 +00:00
render () {
const { avatar, username } = this.props
2015-04-17 10:30:12 +00:00
return <div>
2017-08-23 22:22:00 +00:00
<UserAvatar src={avatar} />
<UserProfile username={username} />
</div>
2015-04-17 10:30:12 +00:00
}
2017-08-23 22:22:00 +00:00
}
2015-04-17 10:30:12 +00:00
```
As of React v16.2.0, fragments can be used to return multiple children without adding extra wrapping nodes to the DOM.
2018-01-24 07:00:35 +00:00
```jsx
import React, {
Component,
Fragment
} from 'react'
class Info extends Component {
2018-01-24 07:00:35 +00:00
render () {
const { avatar, username } = this.props
return (
<Fragment>
<UserAvatar src={avatar} />
<UserProfile username={username} />
</Fragment>
)
2018-01-24 07:00:35 +00:00
}
}
```
{: data-line="5,6,7,8,9,10"}
2015-04-17 10:30:12 +00:00
2017-09-15 09:53:17 +00:00
Nest components to separate concerns.
2017-08-23 22:44:14 +00:00
2017-10-10 15:15:42 +00:00
See: [Composing Components](https://reactjs.org/docs/components-and-props.html#composing-components)
2017-08-23 22:22:00 +00:00
### Children
```jsx
<AlertBox>
<h1>You have pending notifications</h1>
</AlertBox>
```
{: data-line="2"}
```jsx
class AlertBox extends Component {
render () {
return <div className='alert-box'>
{this.props.children}
</div>
}
}
```
{: data-line="4"}
Children are passed as the `children` property.
Defaults
--------
2017-08-23 22:44:14 +00:00
### Setting default props
2014-03-22 04:03:13 +00:00
2017-08-23 22:22:00 +00:00
```jsx
2017-08-24 03:57:09 +00:00
Hello.defaultProps = {
color: 'blue'
2017-08-23 22:44:14 +00:00
}
2015-02-26 07:08:18 +00:00
```
{: data-line="1"}
2014-03-22 04:03:13 +00:00
2017-10-10 15:15:42 +00:00
See: [defaultProps](https://reactjs.org/docs/react-component.html#defaultprops)
2017-08-24 03:57:09 +00:00
2017-08-23 22:44:14 +00:00
### Setting default state
```jsx
class Hello extends Component {
2017-08-23 22:44:14 +00:00
constructor (props) {
super(props)
this.state = { visible: true }
}
}
```
2017-08-24 10:40:09 +00:00
{: data-line="4"}
Set the default state in the `constructor()`.
And without constructor using [Babel](https://babeljs.io/) with [proposal-class-fields](https://github.com/tc39/proposal-class-fields).
```jsx
class Hello extends Component {
state = { visible: true }
}
```
{: data-line="2"}
2017-10-10 15:15:42 +00:00
See: [Setting the default state](https://reactjs.org/docs/react-without-es6.html#setting-the-initial-state)
Other components
----------------
{: .-three-column}
### Functional components
2017-08-24 10:40:09 +00:00
```jsx
function MyComponent ({ name }) {
return <div className='message-box'>
Hello {name}
</div>
2017-08-24 10:40:09 +00:00
}
```
{: data-line="1"}
Functional components have no state. Also, their `props` are passed as the first parameter to a function.
2017-09-15 09:53:17 +00:00
2017-10-10 15:15:42 +00:00
See: [Function and Class Components](https://reactjs.org/docs/components-and-props.html#functional-and-class-components)
### Pure components
2017-08-24 10:40:09 +00:00
```jsx
import React, {PureComponent} from 'react'
class MessageBox extends PureComponent {
···
}
2017-08-24 10:40:09 +00:00
```
{: data-line="3"}
2017-08-24 10:40:09 +00:00
Performance-optimized version of `React.Component`. Doesn't rerender if props/state hasn't changed.
2017-09-15 09:53:17 +00:00
2017-10-10 15:15:42 +00:00
See: [Pure components](https://reactjs.org/docs/react-api.html#react.purecomponent)
2014-03-22 04:03:13 +00:00
2017-08-24 06:53:13 +00:00
### Component API
```jsx
this.forceUpdate()
```
```jsx
this.setState({ ... })
this.setState(state => { ... })
2017-08-24 06:53:13 +00:00
```
```jsx
this.state
this.props
```
2017-10-22 11:08:21 +00:00
These methods and properties are available for `Component` instances.
2017-09-15 09:53:17 +00:00
See: [Component API](http://facebook.github.io/react/docs/component-api.html)
2017-08-24 06:53:13 +00:00
2017-08-23 22:22:00 +00:00
Lifecycle
---------
2017-08-24 03:57:09 +00:00
{: .-two-column}
2014-03-22 04:03:13 +00:00
2015-04-17 10:19:17 +00:00
### Mounting
2020-07-05 13:16:32 +00:00
2020-07-04 13:29:16 +00:00
| Method | Description |
| ------------------------ | ---------------------------------------------------------------------------------------------------- |
| `constructor` _(props)_ | Before rendering [#](https://reactjs.org/docs/react-component.html#constructor) |
| `componentWillMount()` | _Don't use this_ [#](https://reactjs.org/docs/react-component.html#componentwillmount) |
| `render()` | Render [#](https://reactjs.org/docs/react-component.html#render) |
| `componentDidMount()` | After rendering (DOM available) [#](https://reactjs.org/docs/react-component.html#componentdidmount) |
| --- | --- |
| `componentWillUnmount()` | Before DOM removal [#](https://reactjs.org/docs/react-component.html#componentwillunmount) |
| --- | --- |
| `componentDidCatch()` | Catch errors (16+) [#](https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html) |
2017-08-23 22:22:00 +00:00
2017-08-24 03:57:09 +00:00
Set initial the state on `constructor()`.
Add DOM event handlers, timers (etc) on `componentDidMount()`, then remove them on `componentWillUnmount()`.
2015-04-17 10:53:45 +00:00
2015-04-17 10:19:17 +00:00
### Updating
2020-07-05 13:16:32 +00:00
2020-07-04 13:29:16 +00:00
| 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 |
2015-04-17 10:53:45 +00:00
2017-09-15 09:53:17 +00:00
Called when parents change properties and `.setState()`. These are not called for initial renders.
See: [Component specs](http://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops)
2015-04-17 10:19:17 +00:00
2019-04-04 00:22:04 +00:00
Hooks (New)
-----------
{: .-two-column}
### State Hook
```jsx
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
```
{: data-line="5,10"}
Hooks are a new addition in React 16.8.
See: [Hooks at a Glance](https://reactjs.org/docs/hooks-overview.html)
### Declaring multiple state variables
```jsx
2023-01-04 09:44:57 +00:00
import React, { useState } from 'react';
2019-04-04 00:22:04 +00:00
function ExampleWithManyStates() {
// Declare multiple state variables!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
// ...
}
```
### Effect hook
```jsx
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
2020-04-03 20:54:30 +00:00
}, [count]);
2019-04-04 00:22:04 +00:00
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
```
{: data-line="6,7,8,9,10"}
2020-04-03 20:54:30 +00:00
If youre familiar with React class lifecycle methods, you can think of `useEffect` Hook as `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` combined.
2019-04-04 00:22:04 +00:00
By default, React runs the effects after every render — including the first render.
### Building your own hooks
#### Define FriendStatus
```jsx
import React, { useState, useEffect } from 'react';
function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
2020-04-03 20:54:30 +00:00
}, [props.friend.id]);
2019-04-04 00:22:04 +00:00
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
```
{: data-line="11,12,13,14"}
Effects may also optionally specify how to “clean up” after them by returning a function.
#### Use FriendStatus
```jsx
function FriendStatus(props) {
const isOnline = useFriendStatus(props.friend.id);
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
```
{: data-line="2"}
See: [Building Your Own Hooks](https://reactjs.org/docs/hooks-custom.html)
### Hooks API Reference
Also see: [Hooks FAQ](https://reactjs.org/docs/hooks-faq.html)
#### Basic Hooks
2019-12-18 02:34:15 +00:00
| Hook | Description |
| ---------------------------- | ----------------------------------------- |
2019-04-04 00:22:04 +00:00
| `useState`_(initialState)_ | |
| `useEffect`_(() => { ... })_ | |
| `useContext`_(MyContext)_ | value returned from `React.createContext` |
Full details: [Basic Hooks](https://reactjs.org/docs/hooks-reference.html#basic-hooks)
#### Additional Hooks
2019-12-18 02:34:15 +00:00
| Hook | Description |
| -------------------------------------------- | ---------------------------------------------------------------------------- |
2019-04-04 00:22:04 +00:00
| `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 Hooks](https://reactjs.org/docs/hooks-reference.html#additional-hooks)
2017-08-23 22:22:00 +00:00
DOM nodes
---------
2017-08-24 03:57:09 +00:00
{: .-two-column}
2014-03-22 04:03:13 +00:00
2015-04-17 10:19:17 +00:00
### References
2017-08-23 22:30:53 +00:00
```jsx
class MyComponent extends Component {
2017-08-23 22:30:53 +00:00
render () {
return <div>
<input ref={el => this.input = el} />
</div>
}
2017-08-26 16:21:57 +00:00
componentDidMount () {
this.input.focus()
}
2017-08-23 22:30:53 +00:00
}
2015-04-17 10:19:17 +00:00
```
2017-08-26 16:21:57 +00:00
{: data-line="4,9"}
2017-09-15 09:53:17 +00:00
Allows access to DOM nodes.
2017-10-10 15:15:42 +00:00
See: [Refs and the DOM](https://reactjs.org/docs/refs-and-the-dom.html)
2017-08-26 16:21:57 +00:00
### DOM Events
2015-04-17 10:19:17 +00:00
2017-08-23 22:22:00 +00:00
```jsx
class MyComponent extends Component {
2017-08-26 16:21:57 +00:00
render () {
<input type="text"
value={this.state.value}
onChange={event => this.onChange(event)} />
}
onChange (event) {
this.setState({ value: event.target.value })
2017-08-26 16:21:57 +00:00
}
}
2015-04-17 10:19:17 +00:00
```
2017-08-26 16:21:57 +00:00
{: data-line="5,9"}
2014-03-22 04:03:13 +00:00
2017-09-15 09:53:17 +00:00
Pass functions to attributes like `onChange`.
2017-10-10 15:15:42 +00:00
See: [Events](https://reactjs.org/docs/events.html)
2017-08-23 22:22:00 +00:00
2017-08-26 16:21:57 +00:00
## Other features
2017-10-22 11:08:21 +00:00
### Transferring props
2015-04-17 10:19:17 +00:00
```html
2017-08-26 16:21:57 +00:00
<VideoPlayer src="video.mp4" />
```
{: .-setup}
```jsx
class VideoPlayer extends Component {
2017-08-26 16:21:57 +00:00
render () {
return <VideoEmbed {...this.props} />
}
}
2015-04-17 10:19:17 +00:00
```
2017-08-24 10:40:09 +00:00
{: data-line="3"}
2015-04-17 10:19:17 +00:00
2017-08-26 16:21:57 +00:00
Propagates `src="..."` down to the sub-component.
2017-09-15 09:53:17 +00:00
See [Transferring props](http://facebook.github.io/react/docs/transferring-props.html)
2017-08-26 16:21:57 +00:00
### Top-level API
```jsx
React.createClass({ ... })
React.isValidElement(c)
```
```jsx
ReactDOM.render(<Component />, domnode, [callback])
ReactDOM.unmountComponentAtNode(domnode)
```
```jsx
ReactDOMServer.renderToString(<Component />)
ReactDOMServer.renderToStaticMarkup(<Component />)
```
2017-08-31 17:52:22 +00:00
There are more, but these are most common.
2017-09-15 09:53:17 +00:00
2017-10-10 15:15:42 +00:00
See: [React top-level API](https://reactjs.org/docs/react-api.html)
2017-08-31 17:52:22 +00:00
2017-08-26 16:21:57 +00:00
JSX patterns
------------
{: .-two-column}
### Style shorthand
```jsx
const style = { height: 10 }
2017-08-26 16:21:57 +00:00
return <div style={style}></div>
```
2017-08-23 22:22:00 +00:00
```jsx
2017-08-26 16:21:57 +00:00
return <div style={{ margin: 0, padding: 0 }}></div>
```
2017-10-10 15:15:42 +00:00
See: [Inline styles](https://reactjs.org/tips/inline-styles.html)
2017-08-26 16:21:57 +00:00
### Inner HTML
```jsx
function markdownify() { return "<p>...</p>"; }
<div dangerouslySetInnerHTML={{__html: markdownify()}} />
```
2017-10-10 15:15:42 +00:00
See: [Dangerously set innerHTML](https://reactjs.org/tips/dangerously-set-inner-html.html)
2017-08-26 16:21:57 +00:00
### Lists
```jsx
class TodoList extends Component {
2017-08-26 16:21:57 +00:00
render () {
const { items } = this.props
return <ul>
{items.map(item =>
<TodoItem item={item} key={item.key} />)}
</ul>
}
2015-04-17 10:19:17 +00:00
}
```
2017-08-26 16:21:57 +00:00
{: data-line="6,7"}
Always supply a `key` property.
### Conditionals
2015-04-17 10:19:17 +00:00
2017-08-26 16:21:57 +00:00
```jsx
<Fragment>
{showMyComponent
? <MyComponent />
: <OtherComponent />}
</Fragment>
```
### Short-circuit evaluation
```jsx
<Fragment>
{showPopup && <Popup />}
...
</Fragment>
2017-08-26 16:21:57 +00:00
```
2015-04-17 10:19:17 +00:00
2017-09-27 00:19:37 +00:00
New features
------------
{: .-three-column}
### Returning multiple elements
You can return multiple elements as arrays or fragments.
2017-09-27 00:19:37 +00:00
2018-03-26 03:47:31 +00:00
#### Arrays
2017-09-27 00:19:37 +00:00
```js
render () {
// Don't forget the keys!
return [
<li key="A">First item</li>,
<li key="B">Second item</li>
]
}
```
{: data-line="3,4,5,6"}
2018-03-26 03:47:31 +00:00
#### Fragments
```js
render () {
return (
<Fragment>
<li>First item</li>
<li>Second item</li>
</Fragment>
)
}
```
{: data-line="3,4,5,6,7,8"}
2017-09-27 00:19:37 +00:00
2017-10-10 15:15:42 +00:00
See: [Fragments and strings](https://reactjs.org/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings)
2017-09-27 00:19:37 +00:00
### Returning strings
```js
render() {
return 'Look ma, no spans!';
}
```
{: data-line="2"}
You can return just a string.
See: [Fragments and strings](https://reactjs.org/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings)
2017-09-27 00:19:37 +00:00
### Errors
```js
class MyComponent extends Component {
2017-09-27 00:19:37 +00:00
···
componentDidCatch (error, info) {
this.setState({ error })
}
}
```
{: data-line="3,4,5"}
Catch errors via `componentDidCatch`. (React 16+)
2017-10-10 15:15:42 +00:00
See: [Error handling in React 16](https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html)
2017-09-27 00:19:37 +00:00
### Portals
```js
render () {
return React.createPortal(
this.props.children,
document.getElementById('menu')
)
}
```
{: data-line="2,3,4,5"}
This renders `this.props.children` into any location in the DOM.
2017-10-10 15:15:42 +00:00
See: [Portals](https://reactjs.org/docs/portals.html)
2017-09-27 00:19:37 +00:00
### Hydration
```js
const el = document.getElementById('app')
ReactDOM.hydrate(<App />, el)
```
{: data-line="2"}
2017-10-10 15:15:42 +00:00
Use `ReactDOM.hydrate` instead of using `ReactDOM.render` if you're rendering over the output of [ReactDOMServer](https://reactjs.org/docs/react-dom-server.html).
2017-09-27 00:19:37 +00:00
2017-10-10 15:15:42 +00:00
See: [Hydrate](https://reactjs.org/docs/react-dom.html#hydrate)
2017-09-27 00:19:37 +00:00
2017-08-23 22:22:00 +00:00
Property validation
-------------------
2017-08-24 03:57:09 +00:00
{: .-three-column}
2017-08-23 22:22:00 +00:00
2017-08-24 06:53:13 +00:00
### PropTypes
```js
import PropTypes from 'prop-types'
```
2017-08-25 08:10:51 +00:00
{: .-setup}
2017-08-24 06:53:13 +00:00
2017-10-10 15:15:42 +00:00
See: [Typechecking with PropTypes](https://reactjs.org/docs/typechecking-with-proptypes.html)
2017-08-24 06:53:13 +00:00
2020-07-04 13:29:16 +00:00
| Key | Description |
| ----- | ----------- |
| `any` | Anything |
2017-09-21 08:25:42 +00:00
#### Basic
2020-07-04 13:29:16 +00:00
| Key | Description |
| -------- | ------------- |
| `string` | |
| `number` | |
| `func` | Function |
| `bool` | True or false |
2017-09-21 08:25:42 +00:00
#### Enum
2020-07-04 13:29:16 +00:00
| Key | Description |
| ------------------------- | ----------- |
| `oneOf`_(any)_ | Enum types |
| `oneOfType`_(type array)_ | Union |
2017-09-21 08:25:42 +00:00
#### Array
2020-07-04 13:29:16 +00:00
| Key | Description |
| ---------------- | ----------- |
| `array` | |
| `arrayOf`_(...)_ | |
2017-09-21 08:25:42 +00:00
#### Object
2020-07-04 13:29:16 +00:00
| Key | Description |
| ------------------- | ------------------------------------ |
| `object` | |
| `objectOf`_(...)_ | Object with values of a certain type |
| `instanceOf`_(...)_ | Instance of a class |
| `shape`_(...)_ | |
2017-09-21 08:25:42 +00:00
#### Elements
2020-07-04 13:29:16 +00:00
| Key | Description |
| --------- | ------------- |
| `element` | React element |
| `node` | DOM node |
2017-09-21 08:25:42 +00:00
#### Required
2020-07-04 13:29:16 +00:00
| Key | Description |
| ------------------ | ----------- |
| `(···).isRequired` | Required |
2015-04-17 10:19:17 +00:00
### Basic types
2015-02-26 06:17:12 +00:00
2017-08-23 22:22:00 +00:00
```jsx
MyComponent.propTypes = {
2017-08-24 06:53:13 +00:00
email: PropTypes.string,
seats: PropTypes.number,
callback: PropTypes.func,
isClosed: PropTypes.bool,
any: PropTypes.any
2017-08-23 22:22:00 +00:00
}
2015-04-03 05:20:32 +00:00
```
2015-02-26 06:17:12 +00:00
2015-04-17 10:19:17 +00:00
### Required types
2015-02-26 06:17:12 +00:00
2017-08-23 22:22:00 +00:00
```jsx
2017-08-24 03:57:09 +00:00
MyCo.propTypes = {
2017-08-24 06:53:13 +00:00
name: PropTypes.string.isRequired
2017-08-23 22:22:00 +00:00
}
2015-04-17 10:19:17 +00:00
```
2017-08-24 03:57:09 +00:00
### Elements
2015-04-17 10:19:17 +00:00
2017-08-23 22:22:00 +00:00
```jsx
2017-08-24 03:57:09 +00:00
MyCo.propTypes = {
2017-08-23 22:22:00 +00:00
// React element
2017-08-24 06:53:13 +00:00
element: PropTypes.element,
2017-08-23 22:22:00 +00:00
// num, string, element, or an array of those
2017-08-24 06:53:13 +00:00
node: PropTypes.node
2017-08-23 22:22:00 +00:00
}
2015-04-17 10:19:17 +00:00
```
2017-08-24 03:57:09 +00:00
### Enumerables (oneOf)
2015-04-17 10:19:17 +00:00
2017-08-24 03:57:09 +00:00
```jsx
MyCo.propTypes = {
2017-08-24 06:53:13 +00:00
direction: PropTypes.oneOf([
2017-08-24 03:57:09 +00:00
'left', 'right'
])
}
2015-04-17 10:19:17 +00:00
```
2017-08-23 22:22:00 +00:00
2015-04-17 10:19:17 +00:00
### Arrays and objects
2017-08-23 22:22:00 +00:00
```jsx
2017-08-24 03:57:09 +00:00
MyCo.propTypes = {
2017-08-24 06:53:13 +00:00
list: PropTypes.array,
ages: PropTypes.arrayOf(PropTypes.number),
user: PropTypes.object,
user: PropTypes.objectOf(PropTypes.number),
message: PropTypes.instanceOf(Message)
}
```
```jsx
MyCo.propTypes = {
user: PropTypes.shape({
name: PropTypes.string,
age: PropTypes.number
2017-08-24 03:57:09 +00:00
})
}
2015-04-17 10:19:17 +00:00
```
2017-08-23 22:22:00 +00:00
Use `.array[Of]`, `.object[Of]`, `.instanceOf`, `.shape`.
2015-04-17 10:19:17 +00:00
### Custom validation
2017-08-23 22:22:00 +00:00
```jsx
2017-08-24 03:57:09 +00:00
MyCo.propTypes = {
customProp: (props, key, componentName) => {
if (!/matchme/.test(props[key])) {
return new Error('Validation failed!')
2015-02-26 06:17:12 +00:00
}
}
2015-04-17 10:19:17 +00:00
}
2015-02-26 06:17:12 +00:00
```
2017-08-24 03:57:09 +00:00
Also see
--------
2017-08-23 22:22:00 +00:00
2017-10-10 15:15:42 +00:00
* [React website](https://reactjs.org) _(reactjs.org)_
* [React cheatsheet](https://reactcheatsheet.com/) _(reactcheatsheet.com)_
2017-10-10 15:20:14 +00:00
* [Awesome React](https://github.com/enaqx/awesome-react) _(github.com)_
2017-08-28 13:52:26 +00:00
* [React v0.14 cheatsheet](react@0.14) _Legacy version_
2017-08-23 22:22:00 +00:00
2015-04-17 11:01:44 +00:00
{%endraw%}