Appendix B. React cheatsheet

When you develop your own projects, searching on the internet for React documentation and APIs or going back to this book’s chapters to find a single method isn’t efficient. If you’d like to save time and avoid the distractions lurking everywhere on the Net, use this React cheatsheet as a quick reference.

Print-ready PDF available

In addition to the text version presented here, I’ve created a free beautifully designed, print-ready PDF version of this cheatsheet. You can request this PDF at http://reactquickly.co/resources.

Installation

React

  • <script src="https://unpkg.com/react@15/dist/react.js"></script>
  • $ npm install react --save
  • $ bower install react --save

React DOM

  • <script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
  • $ npm install react-dom
  • $ bower install react-dom --save

Rendering

ES5

ReactDOM.render(
    React.createElement(
      Link,
      {href: 'https://Node.University'}
    )
  ),
  document.getElementById('menu')
)

ES5+JSX

ReactDOM.render(
  <Link href='https://Node.University'/>,
  document.getElementById('menu')
)

Server-side rendering

const ReactDOMServer = require('react-dom/server')
ReactDOMServer.renderToString(Link, {href: 'https://Node.University'})
ReactDOMServer.renderToStaticMarkup(Link, {href: 'https://Node.University'})

Components

ES5

var Link = React.createClass({
  displayName: 'Link',
  render: function() {
    return React.createElement('a',
      {className: 'btn', href: this.props.href}, 'Click ->', this.props.href)
  }
})

ES5 + JSX

var Link = React.createClass({
  render: function() {
    return <a className='btn' href={this.props.href}>Click ->
      this.props.href</a>
  }
})

ES6 + JSX

class Link extends React.Component {
  render() {
    return <a className='btn' href={this.props.href}>Click ->
      this.props.href</a>
  }
}

Advanced components

Options (ES5)

  • Type validation in development modepropTypes object
  • Object of default propertiesgetDefaultProps function()
  • Object of the initial stategetInitialState function()

ES5

var Link = React.createClass ({
  propTypes: { href: React.PropTypes.string },
  getDefaultProps: function() {
    return { initialCount: 0 }
  },
  getInitialState: function() {
    return {count: this.props.initialCount}
  },
  tick: function() {
    this.setState({count: this.state.count + 1})
  },
  render: function() {
    return React.createElement(
      'a',
      {className: 'btn', href: '#', href: this.props.href,
        onClick: this.tick.bind(this)},
      'Click ->',
      (this.props.href ? this.props.href : 'https://webapplog.com'),
      ' (Clicked: ' + this.state.count+')'
    )
  }
})

ES5 + JSX

var Link = React.createClass ({
  propTypes: { href: React.PropTypes.string },
  getDefaultProps: function() {
    return { initialCount: 0 }
  },
  getInitialState: function() {
    return {count: this.props.initialCount};
  },
  tick: function() {
    this.setState({count: this.state.count + 1})
  },
  render: function() {
    return (
      <a onClick={this.tick.bind(this)} href="#" className="btn"
        href={this.props.href}>
        Click -> {(this.props.href ? this.props.href :
         'https://webapplog.com')}
        (Clicked: {this.state.count})
      </a>
    )
  }
})

ES6 + JSX

export class Link extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
  }
  tick() {
    this.setState({count: this.state.count + 1});
  }
  render() {
    return (
      <a onClick={this.tick.bind(this)} href="#" className="btn"
        href={this.props.href}>
        Click -> {(this.props.href ? this.props.href :
          'https://webapplog.com')}
        (Clicked: {this.state.count})
      </a>
    )
  }
}
Link.propTypes = { initialCount: React.PropTypes.number }
Link.defaultProps = { initialCount: 0 }

Lifecycle events

  • componentWillMount function()
  • componentDidMount function()
  • componentWillReceiveProps function(nextProps)
  • shouldComponentUpdate function(nextProps, nextState)bool
  • componentWillUpdate function(nextProps, nextState)
  • componentDidUpdate function(prevProps, prevState)
  • componentWillUnmount function()

Sequence of lifecycle events (inspired by http://react.tips)

Mounting

Updating component properties

Updating component state

Using forceUpdate()

Unmounting

getDefaultProps()        
getInitialState()        
componentWillMount()        
  componentWillReceiveProps()      
  shouldComponentUpdate() shouldComponentUpdate()    
  componentWillUpdate() componentWillUpdate() componentWillUpdate()  
render() render() render() render()  
  componentDidUpdate() componentDidUpdate() componentDidUpdate()  
componentDidMount()        
        componentWillUnmount()

Special properties

  • key—Unique identifier for an element to turn arrays/lists into hashes for better performance. For example: key={id}.
  • ref—Reference to an element via this.refs.NAME. For example: ref="email" will create a this.refs.email DOM node or ReactDOM.findDOMNode(this.refs.email).
  • style—Accepts an object for camelCased CSS styles instead of a string (immutable since v0.14). For example: style={{color: red}}.
  • className—HTML class attribute. For example: className="btn".
  • htmlFor—HTML for attribute. For example: htmlFor="email".
  • dangerouslySetInnerHTML—Sets inner HTML to raw HTML by providing an object with the key __html.
  • children—Sets the content of the element via this.props.children. For example: this.props.children[0].
  • data-NAME—Custom attribute. For example: data-tooltip-text="...".

propTypes

Types available under React.PropTypes:

  • any
  • array
  • bool
  • element
  • func
  • node
  • number
  • object
  • string

To make a property required (warning only), append .isRequired.

More methods:

  • instanceOf(constructor)
  • oneOf(['News', 'Photos'])
  • oneOfType([propType, propType])

Custom validation

propTypes: {
  customProp: function(props, propName, componentName) {
    if (!/regExPattern/.test(props[propName])) {
      return new Error('Validation failed!');
    }
  }
}

Component properties and methods

Properties

  • this.refs—Lists components with a ref property.
  • this.props—Lists any properties passed to an element (immutable).
  • this.state—Lists states set by setState and getInitialState (mutable). Avoid setting state manually with this.state=....
  • this.isMounted—Flags whether the element has a corresponding DOM node.

Methods

  • setState(changes)—Changes state (partially) to this.state, and triggers a rerender
  • replaceState(newState)—Replaces this.state, and triggers a rerender
  • forceUpdate()—Triggers an immediate DOM rerender

React add-ons

As npm modules:

React components

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.104.238