14 - dangerouslySetInnerHTML
16 [React](https://reactjs.org/) is a JavaScript library for building user interfaces. This guide targets React v15 to v16.
29 import React from 'react'
30 import ReactDOM from 'react-dom'
35 class Hello extends React.Component {
37 return <div className='message-box'>
38 Hello {this.props.name}
45 const el = document.body
46 ReactDOM.render(<Hello name='John' />, el)
49 Use the [React.js jsfiddle](http://jsfiddle.net/reactjs/69z2wepo/) to start hacking. (or the unofficial [jsbin](http://jsbin.com/yafixat/edit?js,output))
51 ### Import multiple exports
55 import React, {Component} from 'react'
56 import ReactDOM from 'react-dom'
61 class Hello extends Component {
69 <Video fullscreen={true} autoplay={false} />
76 const { fullscreen, autoplay } = this.props
82 Use `this.props` to access properties passed to the component.
84 See: [Properties](https://reactjs.org/docs/tutorial.html#using-props)
91 this.state = { username: undefined }
96 this.setState({ username: 'rstacruz' })
102 const { username } = this.state
108 Use states (`this.state`) to manage dynamic data.
110 With [Babel](https://babeljs.io/) you can use [proposal-class-fields](https://github.com/tc39/proposal-class-fields) and get rid of constructor
113 class Hello extends Component {
114 state = { username: undefined };
119 See: [States](https://reactjs.org/docs/tutorial.html#reactive-state)
125 class Info extends Component {
127 const { avatar, username } = this.props
130 <UserAvatar src={avatar} />
131 <UserProfile username={username} />
136 As of React v16.2.0, fragments can be used to return multiple children without adding extra wrapping nodes to the DOM.
144 class Info extends Component {
146 const { avatar, username } = this.props
150 <UserAvatar src={avatar} />
151 <UserProfile username={username} />
159 {: data-line="5,6,7,8,9,10"}
161 Nest components to separate concerns.
163 See: [Composing Components](https://reactjs.org/docs/components-and-props.html#composing-components)
169 <h1>You have pending notifications</h1>
175 class AlertBox extends Component {
177 return <div className='alert-box'>
178 {this.props.children}
185 Children are passed as the `children` property.
190 ### Setting default props
193 Hello.defaultProps = {
199 See: [defaultProps](https://reactjs.org/docs/react-component.html#defaultprops)
201 ### Setting default state
204 class Hello extends Component {
205 constructor (props) {
207 this.state = { visible: true }
213 Set the default state in the `constructor()`.
215 And without constructor using [Babel](https://babeljs.io/) with [proposal-class-fields](https://github.com/tc39/proposal-class-fields).
218 class Hello extends Component {
219 state = { visible: true }
226 See: [Setting the default state](https://reactjs.org/docs/react-without-es6.html#setting-the-initial-state)
232 ### Functional components
235 function MyComponent ({ name }) {
236 return <div className='message-box'>
243 Functional components have no state. Also, their `props` are passed as the first parameter to a function.
245 See: [Function and Class Components](https://reactjs.org/docs/components-and-props.html#functional-and-class-components)
250 import React, {PureComponent} from 'react'
252 class MessageBox extends PureComponent {
258 Performance-optimized version of `React.Component`. Doesn't rerender if props/state hasn't changed.
260 See: [Pure components](https://reactjs.org/docs/react-api.html#react.purecomponent)
269 this.setState({ ... })
270 this.setState(state => { ... })
278 These methods and properties are available for `Component` instances.
280 See: [Component API](http://facebook.github.io/react/docs/component-api.html)
288 | Method | Description |
290 | `constructor` _(props)_ | Before rendering [#](https://reactjs.org/docs/react-component.html#constructor) |
291 | `componentWillMount()` | _Don't use this_ [#](https://reactjs.org/docs/react-component.html#componentwillmount) |
292 | `render()` | Render [#](https://reactjs.org/docs/react-component.html#render) |
293 | `componentDidMount()` | After rendering (DOM available) [#](https://reactjs.org/docs/react-component.html#componentdidmount) |
295 | `componentWillUnmount()` | Before DOM removal [#](https://reactjs.org/docs/react-component.html#componentwillunmount) |
297 | `componentDidCatch()` | Catch errors (16+) [#](https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html) |
299 Set initial the state on `constructor()`.
300 Add DOM event handlers, timers (etc) on `componentDidMount()`, then remove them on `componentWillUnmount()`.
304 | Method | Description |
306 | `componentDidUpdate` *(prevProps, prevState, snapshot)* | Use `setState()` here, but remember to compare props |
307 | `shouldComponentUpdate` *(newProps, newState)* | Skips `render()` if returns false |
308 | `render()` | Render |
309 | `componentDidUpdate` *(prevProps, prevState)* | Operate on the DOM here |
311 Called when parents change properties and `.setState()`. These are not called for initial renders.
313 See: [Component specs](http://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops)
322 import React, { useState } from 'react';
325 // Declare a new state variable, which we'll call "count"
326 const [count, setCount] = useState(0);
330 <p>You clicked {count} times</p>
331 <button onClick={() => setCount(count + 1)}>
340 Hooks are a new addition in React 16.8.
342 See: [Hooks at a Glance](https://reactjs.org/docs/hooks-overview.html)
344 ### Declaring multiple state variables
347 function ExampleWithManyStates() {
348 // Declare multiple state variables!
349 const [age, setAge] = useState(42);
350 const [fruit, setFruit] = useState('banana');
351 const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
359 import React, { useState, useEffect } from 'react';
362 const [count, setCount] = useState(0);
364 // Similar to componentDidMount and componentDidUpdate:
366 // Update the document title using the browser API
367 document.title = `You clicked ${count} times`;
372 <p>You clicked {count} times</p>
373 <button onClick={() => setCount(count + 1)}>
380 {: data-line="6,7,8,9,10"}
382 If you’re familiar with React class lifecycle methods, you can think of `useEffect` Hook as `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` combined.
384 By default, React runs the effects after every render — including the first render.
386 ### Building your own hooks
388 #### Define FriendStatus
390 import React, { useState, useEffect } from 'react';
392 function FriendStatus(props) {
393 const [isOnline, setIsOnline] = useState(null);
396 function handleStatusChange(status) {
397 setIsOnline(status.isOnline);
400 ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
402 ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
406 if (isOnline === null) {
409 return isOnline ? 'Online' : 'Offline';
412 {: data-line="11,12,13,14"}
414 Effects may also optionally specify how to “clean up” after them by returning a function.
416 #### Use FriendStatus
419 function FriendStatus(props) {
420 const isOnline = useFriendStatus(props.friend.id);
422 if (isOnline === null) {
425 return isOnline ? 'Online' : 'Offline';
430 See: [Building Your Own Hooks](https://reactjs.org/docs/hooks-custom.html)
432 ### Hooks API Reference
434 Also see: [Hooks FAQ](https://reactjs.org/docs/hooks-faq.html)
438 | Hook | Description |
439 | ---------------------------- | ----------------------------------------- |
440 | `useState`_(initialState)_ | |
441 | `useEffect`_(() => { ... })_ | |
442 | `useContext`_(MyContext)_ | value returned from `React.createContext` |
444 Full details: [Basic Hooks](https://reactjs.org/docs/hooks-reference.html#basic-hooks)
446 #### Additional Hooks
448 | Hook | Description |
449 | -------------------------------------------- | ---------------------------------------------------------------------------- |
450 | `useReducer`_(reducer, initialArg, init)_ | |
451 | `useCallback`_(() => { ... })_ | |
452 | `useMemo`_(() => { ... })_ | |
453 | `useRef`_(initialValue)_ | |
454 | `useImperativeHandle`_(ref, () => { ... })_ | |
455 | `useLayoutEffect` | identical to `useEffect`, but it fires synchronously after all DOM mutations |
456 | `useDebugValue`_(value)_ | display a label for custom hooks in React DevTools |
458 Full details: [Additional Hooks](https://reactjs.org/docs/hooks-reference.html#additional-hooks)
467 class MyComponent extends Component {
470 <input ref={el => this.input = el} />
474 componentDidMount () {
481 Allows access to DOM nodes.
483 See: [Refs and the DOM](https://reactjs.org/docs/refs-and-the-dom.html)
488 class MyComponent extends Component {
491 value={this.state.value}
492 onChange={event => this.onChange(event)} />
496 this.setState({ value: event.target.value })
502 Pass functions to attributes like `onChange`.
504 See: [Events](https://reactjs.org/docs/events.html)
508 ### Transferring props
511 <VideoPlayer src="video.mp4" />
516 class VideoPlayer extends Component {
518 return <VideoEmbed {...this.props} />
524 Propagates `src="..."` down to the sub-component.
526 See [Transferring props](http://facebook.github.io/react/docs/transferring-props.html)
531 React.createClass({ ... })
532 React.isValidElement(c)
536 ReactDOM.render(<Component />, domnode, [callback])
537 ReactDOM.unmountComponentAtNode(domnode)
541 ReactDOMServer.renderToString(<Component />)
542 ReactDOMServer.renderToStaticMarkup(<Component />)
545 There are more, but these are most common.
547 See: [React top-level API](https://reactjs.org/docs/react-api.html)
556 const style = { height: 10 }
557 return <div style={style}></div>
561 return <div style={{ margin: 0, padding: 0 }}></div>
564 See: [Inline styles](https://reactjs.org/tips/inline-styles.html)
569 function markdownify() { return "<p>...</p>"; }
570 <div dangerouslySetInnerHTML={{__html: markdownify()}} />
573 See: [Dangerously set innerHTML](https://reactjs.org/tips/dangerously-set-inner-html.html)
578 class TodoList extends Component {
580 const { items } = this.props
584 <TodoItem item={item} key={item.key} />)}
591 Always supply a `key` property.
599 : <OtherComponent />}
603 ### Short-circuit evaluation
607 {showPopup && <Popup />}
616 ### Returning multiple elements
618 You can return multiple elements as arrays or fragments.
624 // Don't forget the keys!
626 <li key="A">First item</li>,
627 <li key="B">Second item</li>
631 {: data-line="3,4,5,6"}
636 // Fragments don't require keys!
645 {: data-line="3,4,5,6,7,8"}
647 See: [Fragments and strings](https://reactjs.org/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings)
649 ### Returning strings
653 return 'Look ma, no spans!';
658 You can return just a string.
660 See: [Fragments and strings](https://reactjs.org/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings)
665 class MyComponent extends Component {
667 componentDidCatch (error, info) {
668 this.setState({ error })
672 {: data-line="3,4,5"}
674 Catch errors via `componentDidCatch`. (React 16+)
676 See: [Error handling in React 16](https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html)
682 return React.createPortal(
684 document.getElementById('menu')
688 {: data-line="2,3,4,5"}
690 This renders `this.props.children` into any location in the DOM.
692 See: [Portals](https://reactjs.org/docs/portals.html)
697 const el = document.getElementById('app')
698 ReactDOM.hydrate(<App />, el)
702 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).
704 See: [Hydrate](https://reactjs.org/docs/react-dom.html#hydrate)
713 import PropTypes from 'prop-types'
717 See: [Typechecking with PropTypes](https://reactjs.org/docs/typechecking-with-proptypes.html)
725 | `func` | Function |
726 | `bool` | True or false |
730 | `oneOf`_(any)_ | Enum types |
731 | `oneOfType`_(type array)_ | Union |
736 | `arrayOf`_(...)_ | |
741 | `objectOf`_(...)_ | Object with values of a certain type |
742 | `instanceOf`_(...)_ | Instance of a class |
747 | `element` | React element |
748 | `node` | DOM node |
752 | `(···).isRequired` | Required |
757 MyComponent.propTypes = {
758 email: PropTypes.string,
759 seats: PropTypes.number,
760 callback: PropTypes.func,
761 isClosed: PropTypes.bool,
770 name: PropTypes.string.isRequired
779 element: PropTypes.element,
781 // num, string, element, or an array of those
786 ### Enumerables (oneOf)
790 direction: PropTypes.oneOf([
796 ### Arrays and objects
800 list: PropTypes.array,
801 ages: PropTypes.arrayOf(PropTypes.number),
802 user: PropTypes.object,
803 user: PropTypes.objectOf(PropTypes.number),
804 message: PropTypes.instanceOf(Message)
810 user: PropTypes.shape({
811 name: PropTypes.string,
812 age: PropTypes.number
817 Use `.array[Of]`, `.object[Of]`, `.instanceOf`, `.shape`.
819 ### Custom validation
823 customProp: (props, key, componentName) => {
824 if (!/matchme/.test(props[key])) {
825 return new Error('Validation failed!')
834 * [React website](https://reactjs.org) _(reactjs.org)_
835 * [React cheatsheet](https://reactcheatsheet.com/) _(reactcheatsheet.com)_
836 * [Awesome React](https://github.com/enaqx/awesome-react) _(github.com)_
837 * [React v0.14 cheatsheet](react@0.14) _Legacy version_