React.js Reusability Checklist & General Cheat Sheet
class MyComponent extends Component {
static propTypes = {}
static defaultProps = {}
constructor(props) {
super(props);
this.state = { // state keys go here }
}
render() { }
}
function MyComponent(props) {
return ( <div></div>);
}
constructor() |
Called before component is mounted
|
render() |
Never call setState() here
|
componentWillMount() |
Before rendering (no DOM yet)
|
componentDidMount() |
After rendering
|
componentWillUpdate() |
Can’t use
setState() here |
componentDidUpdate() |
Operate on the DOM here
|
componentWillReceiveProps() |
Use
setState() here |
shouldComponentUpdate() |
Skips
render() if returns false |
PropTypes.array |
Check if prop is an array
|
PropTypes.string |
Check if prop is a string
|
PropTypes.bool |
Check if prop is a boolean (true/false)
|
PropTypes.number |
Check if prop is a number
|
PropTypes.object |
Check if prop is an object
|
PropTypes.node |
Check if prop is anything that can
be rendered in a React component |
PropTypes.func |
Check if prop is a function
|
PropTypes.element |
Check if prop is a React element
|
PropTypes.oneOf(['M', 'F'']) |
Check if prop matches one of
these values |
PropTypes.oneOfType([ |
Check if prop matches one of
these types |
PropTypes.instanceOf(Class) |
Check if prop is an instance of a class
|
PropTypes.arrayOf(Array) |
Check if prop is an array of
some specific type |
PropTypes.objectOf(PropTypes.number) |
Check if prop is an object with
property values of a specific type |
PropTypes.shape({ |
Check if prop object has a
particular "shape" |
PropTypes.any |
Check if anything at all is passed
|
|
Step #1 -Define your component and import PropTypes
from the 'prop-types' package import React, { Component } from 'react';
|
|
Step #2 - Define the props & what type they are
...
|
|
Step #3 - Determine which props are required or optional
...
|
|
Step #4 - Define the defaults (if applicable)
...
|
...
static propTypes: {
email: ((props, propName) => {
const regex = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if (!regex.test(props[propName])) {
return new Error('Invalid email!');
}
})
}
...
setState(updater, [callback]) |
Component will re-render
with new state |
forceUpdate() |
Calls
render(), skips shouldComponentUpdate() |
|
Knowing how to create reusable components is step 1.
|
|
Then you need to learn how to architect professional apps using React & Redux.
|
|
Learn how at www.singlepageapplication.com
|
No comments yet.
Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.