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} />
158 {: data-line="5,6,7,8,9,10"}
160 Nest components to separate concerns.
162 See: [Composing Components](https://reactjs.org/docs/components-and-props.html#composing-components)
168 <h1>You have pending notifications</h1>
174 class AlertBox extends Component {
176 return <div className='alert-box'>
177 {this.props.children}
184 Children are passed as the `children` property.
189 ### Setting default props
192 Hello.defaultProps = {
198 See: [defaultProps](https://reactjs.org/docs/react-component.html#defaultprops)
200 ### Setting default state
203 class Hello extends Component {
204 constructor (props) {
206 this.state = { visible: true }
212 Set the default state in the `constructor()`.
214 And without constructor using [Babel](https://babeljs.io/) with [proposal-class-fields](https://github.com/tc39/proposal-class-fields).
217 class Hello extends Component {
218 state = { visible: true }
223 See: [Setting the default state](https://reactjs.org/docs/react-without-es6.html#setting-the-initial-state)
229 ### Functional components
232 function MyComponent ({ name }) {
233 return <div className='message-box'>
240 Functional components have no state. Also, their `props` are passed as the first parameter to a function.
242 See: [Function and Class Components](https://reactjs.org/docs/components-and-props.html#functional-and-class-components)
247 import React, {PureComponent} from 'react'
249 class MessageBox extends PureComponent {
255 Performance-optimized version of `React.Component`. Doesn't rerender if props/state hasn't changed.
257 See: [Pure components](https://reactjs.org/docs/react-api.html#react.purecomponent)
266 this.setState({ ... })
267 this.setState(state => { ... })
275 These methods and properties are available for `Component` instances.
277 See: [Component API](http://facebook.github.io/react/docs/component-api.html)
285 | Method | Description |
286 | ------------------------ | ---------------------------------------------------------------------------------------------------- |
287 | `constructor` _(props)_ | Before rendering [#](https://reactjs.org/docs/react-component.html#constructor) |
288 | `componentWillMount()` | _Don't use this_ [#](https://reactjs.org/docs/react-component.html#componentwillmount) |
289 | `render()` | Render [#](https://reactjs.org/docs/react-component.html#render) |
290 | `componentDidMount()` | After rendering (DOM available) [#](https://reactjs.org/docs/react-component.html#componentdidmount) |
292 | `componentWillUnmount()` | Before DOM removal [#](https://reactjs.org/docs/react-component.html#componentwillunmount) |
294 | `componentDidCatch()` | Catch errors (16+) [#](https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html) |
296 Set initial the state on `constructor()`.
297 Add DOM event handlers, timers (etc) on `componentDidMount()`, then remove them on `componentWillUnmount()`.
301 | Method | Description |
302 | ------------------------------------------------------- | ---------------------------------------------------- |
303 | `componentDidUpdate` _(prevProps, prevState, snapshot)_ | Use `setState()` here, but remember to compare props |
304 | `shouldComponentUpdate` _(newProps, newState)_ | Skips `render()` if returns false |
305 | `render()` | Render |
306 | `componentDidUpdate` _(prevProps, prevState)_ | Operate on the DOM here |
308 Called when parents change properties and `.setState()`. These are not called for initial renders.
310 See: [Component specs](http://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops)
319 import React, { useState } from 'react';
322 // Declare a new state variable, which we'll call "count"
323 const [count, setCount] = useState(0);
327 <p>You clicked {count} times</p>
328 <button onClick={() => setCount(count + 1)}>
337 Hooks are a new addition in React 16.8.
339 See: [Hooks at a Glance](https://reactjs.org/docs/hooks-overview.html)
341 ### Declaring multiple state variables
344 function ExampleWithManyStates() {
345 // Declare multiple state variables!
346 const [age, setAge] = useState(42);
347 const [fruit, setFruit] = useState('banana');
348 const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
356 import React, { useState, useEffect } from 'react';
359 const [count, setCount] = useState(0);
361 // Similar to componentDidMount and componentDidUpdate:
363 // Update the document title using the browser API
364 document.title = `You clicked ${count} times`;
369 <p>You clicked {count} times</p>
370 <button onClick={() => setCount(count + 1)}>
377 {: data-line="6,7,8,9,10"}
379 If you’re familiar with React class lifecycle methods, you can think of `useEffect` Hook as `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` combined.
381 By default, React runs the effects after every render — including the first render.
383 ### Building your own hooks
385 #### Define FriendStatus
387 import React, { useState, useEffect } from 'react';
389 function FriendStatus(props) {
390 const [isOnline, setIsOnline] = useState(null);
393 function handleStatusChange(status) {
394 setIsOnline(status.isOnline);
397 ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
399 ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
401 }, [props.friend.id]);
403 if (isOnline === null) {
406 return isOnline ? 'Online' : 'Offline';
409 {: data-line="11,12,13,14"}
411 Effects may also optionally specify how to “clean up” after them by returning a function.
413 #### Use FriendStatus
416 function FriendStatus(props) {
417 const isOnline = useFriendStatus(props.friend.id);
419 if (isOnline === null) {
422 return isOnline ? 'Online' : 'Offline';
427 See: [Building Your Own Hooks](https://reactjs.org/docs/hooks-custom.html)
429 ### Hooks API Reference
431 Also see: [Hooks FAQ](https://reactjs.org/docs/hooks-faq.html)
435 | Hook | Description |
436 | ---------------------------- | ----------------------------------------- |
437 | `useState`_(initialState)_ | |
438 | `useEffect`_(() => { ... })_ | |
439 | `useContext`_(MyContext)_ | value returned from `React.createContext` |
441 Full details: [Basic Hooks](https://reactjs.org/docs/hooks-reference.html#basic-hooks)
443 #### Additional Hooks
445 | Hook | Description |
446 | -------------------------------------------- | ---------------------------------------------------------------------------- |
447 | `useReducer`_(reducer, initialArg, init)_ | |
448 | `useCallback`_(() => { ... })_ | |
449 | `useMemo`_(() => { ... })_ | |
450 | `useRef`_(initialValue)_ | |
451 | `useImperativeHandle`_(ref, () => { ... })_ | |
452 | `useLayoutEffect` | identical to `useEffect`, but it fires synchronously after all DOM mutations |
453 | `useDebugValue`_(value)_ | display a label for custom hooks in React DevTools |
455 Full details: [Additional Hooks](https://reactjs.org/docs/hooks-reference.html#additional-hooks)
464 class MyComponent extends Component {
467 <input ref={el => this.input = el} />
471 componentDidMount () {
478 Allows access to DOM nodes.
480 See: [Refs and the DOM](https://reactjs.org/docs/refs-and-the-dom.html)
485 class MyComponent extends Component {
488 value={this.state.value}
489 onChange={event => this.onChange(event)} />
493 this.setState({ value: event.target.value })
499 Pass functions to attributes like `onChange`.
501 See: [Events](https://reactjs.org/docs/events.html)
505 ### Transferring props
508 <VideoPlayer src="video.mp4" />
513 class VideoPlayer extends Component {
515 return <VideoEmbed {...this.props} />
521 Propagates `src="..."` down to the sub-component.
523 See [Transferring props](http://facebook.github.io/react/docs/transferring-props.html)
528 React.createClass({ ... })
529 React.isValidElement(c)
533 ReactDOM.render(<Component />, domnode, [callback])
534 ReactDOM.unmountComponentAtNode(domnode)
538 ReactDOMServer.renderToString(<Component />)
539 ReactDOMServer.renderToStaticMarkup(<Component />)
542 There are more, but these are most common.
544 See: [React top-level API](https://reactjs.org/docs/react-api.html)
553 const style = { height: 10 }
554 return <div style={style}></div>
558 return <div style={{ margin: 0, padding: 0 }}></div>
561 See: [Inline styles](https://reactjs.org/tips/inline-styles.html)
566 function markdownify() { return "<p>...</p>"; }
567 <div dangerouslySetInnerHTML={{__html: markdownify()}} />
570 See: [Dangerously set innerHTML](https://reactjs.org/tips/dangerously-set-inner-html.html)
575 class TodoList extends Component {
577 const { items } = this.props
581 <TodoItem item={item} key={item.key} />)}
588 Always supply a `key` property.
596 : <OtherComponent />}
600 ### Short-circuit evaluation
604 {showPopup && <Popup />}
613 ### Returning multiple elements
615 You can return multiple elements as arrays or fragments.
621 // Don't forget the keys!
623 <li key="A">First item</li>,
624 <li key="B">Second item</li>
628 {: data-line="3,4,5,6"}
633 // Fragments don't require keys!
642 {: data-line="3,4,5,6,7,8"}
644 See: [Fragments and strings](https://reactjs.org/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings)
646 ### Returning strings
650 return 'Look ma, no spans!';
655 You can return just a string.
657 See: [Fragments and strings](https://reactjs.org/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings)
662 class MyComponent extends Component {
664 componentDidCatch (error, info) {
665 this.setState({ error })
669 {: data-line="3,4,5"}
671 Catch errors via `componentDidCatch`. (React 16+)
673 See: [Error handling in React 16](https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html)
679 return React.createPortal(
681 document.getElementById('menu')
685 {: data-line="2,3,4,5"}
687 This renders `this.props.children` into any location in the DOM.
689 See: [Portals](https://reactjs.org/docs/portals.html)
694 const el = document.getElementById('app')
695 ReactDOM.hydrate(<App />, el)
699 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).
701 See: [Hydrate](https://reactjs.org/docs/react-dom.html#hydrate)
710 import PropTypes from 'prop-types'
714 See: [Typechecking with PropTypes](https://reactjs.org/docs/typechecking-with-proptypes.html)
716 | Key | Description |
717 | ----- | ----------- |
722 | Key | Description |
723 | -------- | ------------- |
726 | `func` | Function |
727 | `bool` | True or false |
731 | Key | Description |
732 | ------------------------- | ----------- |
733 | `oneOf`_(any)_ | Enum types |
734 | `oneOfType`_(type array)_ | Union |
738 | Key | Description |
739 | ---------------- | ----------- |
741 | `arrayOf`_(...)_ | |
745 | Key | Description |
746 | ------------------- | ------------------------------------ |
748 | `objectOf`_(...)_ | Object with values of a certain type |
749 | `instanceOf`_(...)_ | Instance of a class |
754 | Key | Description |
755 | --------- | ------------- |
756 | `element` | React element |
757 | `node` | DOM node |
761 | Key | Description |
762 | ------------------ | ----------- |
763 | `(···).isRequired` | Required |
768 MyComponent.propTypes = {
769 email: PropTypes.string,
770 seats: PropTypes.number,
771 callback: PropTypes.func,
772 isClosed: PropTypes.bool,
781 name: PropTypes.string.isRequired
790 element: PropTypes.element,
792 // num, string, element, or an array of those
797 ### Enumerables (oneOf)
801 direction: PropTypes.oneOf([
807 ### Arrays and objects
811 list: PropTypes.array,
812 ages: PropTypes.arrayOf(PropTypes.number),
813 user: PropTypes.object,
814 user: PropTypes.objectOf(PropTypes.number),
815 message: PropTypes.instanceOf(Message)
821 user: PropTypes.shape({
822 name: PropTypes.string,
823 age: PropTypes.number
828 Use `.array[Of]`, `.object[Of]`, `.instanceOf`, `.shape`.
830 ### Custom validation
834 customProp: (props, key, componentName) => {
835 if (!/matchme/.test(props[key])) {
836 return new Error('Validation failed!')
845 * [React website](https://reactjs.org) _(reactjs.org)_
846 * [React cheatsheet](https://reactcheatsheet.com/) _(reactcheatsheet.com)_
847 * [Awesome React](https://github.com/enaqx/awesome-react) _(github.com)_
848 * [React v0.14 cheatsheet](react@0.14) _Legacy version_