[
  {
    "path": ".gitignore",
    "content": "_book\nnode_modules\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "> Your contributions are heartily ♡ welcome. (✿◠‿◠)\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "Creative Commons Attribution 4.0 International\n\n=======================================================================\n\nCreative Commons Corporation (\"Creative Commons\") is not a law firm and\ndoes not provide legal services or legal advice. Distribution of\nCreative Commons public licenses does not create a lawyer-client or\nother relationship. Creative Commons makes its licenses and related\ninformation available on an \"as-is\" basis. Creative Commons gives no\nwarranties regarding its licenses, any material licensed under their\nterms and conditions, or any related information. Creative Commons\ndisclaims all liability for damages resulting from their use to the\nfullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and\nconditions that creators and other rights holders may use to share\noriginal works of authorship and other material subject to copyright\nand certain other rights specified in the public license below. The\nfollowing considerations are for informational purposes only, are not\nexhaustive, and do not form part of our licenses.\n\n     Considerations for licensors: Our public licenses are\n     intended for use by those authorized to give the public\n     permission to use material in ways otherwise restricted by\n     copyright and certain other rights. Our licenses are\n     irrevocable. Licensors should read and understand the terms\n     and conditions of the license they choose before applying it.\n     Licensors should also secure all rights necessary before\n     applying our licenses so that the public can reuse the\n     material as expected. Licensors should clearly mark any\n     material not subject to the license. This includes other CC-\n     licensed material, or material used under an exception or\n     limitation to copyright. More considerations for licensors:\n  wiki.creativecommons.org/Considerations_for_licensors\n\n     Considerations for the public: By using one of our public\n     licenses, a licensor grants the public permission to use the\n     licensed material under specified terms and conditions. If\n     the licensor's permission is not necessary for any reason--for\n     example, because of any applicable exception or limitation to\n     copyright--then that use is not regulated by the license. Our\n     licenses grant only permissions under copyright and certain\n     other rights that a licensor has authority to grant. Use of\n     the licensed material may still be restricted for other\n     reasons, including because others have copyright or other\n     rights in the material. A licensor may make special requests,\n     such as asking that all changes be marked or described.\n     Although not required by our licenses, you are encouraged to\n     respect those requests where reasonable. More_considerations\n     for the public:\n  wiki.creativecommons.org/Considerations_for_licensees\n\n=======================================================================\n\nCreative Commons Attribution 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree\nto be bound by the terms and conditions of this Creative Commons\nAttribution 4.0 International Public License (\"Public License\"). To the\nextent this Public License may be interpreted as a contract, You are\ngranted the Licensed Rights in consideration of Your acceptance of\nthese terms and conditions, and the Licensor grants You such rights in\nconsideration of benefits the Licensor receives from making the\nLicensed Material available under these terms and conditions.\n\n\nSection 1 -- Definitions.\n\n  a. Adapted Material means material subject to Copyright and Similar\n     Rights that is derived from or based upon the Licensed Material\n     and in which the Licensed Material is translated, altered,\n     arranged, transformed, or otherwise modified in a manner requiring\n     permission under the Copyright and Similar Rights held by the\n     Licensor. For purposes of this Public License, where the Licensed\n     Material is a musical work, performance, or sound recording,\n     Adapted Material is always produced where the Licensed Material is\n     synched in timed relation with a moving image.\n\n  b. Adapter's License means the license You apply to Your Copyright\n     and Similar Rights in Your contributions to Adapted Material in\n     accordance with the terms and conditions of this Public License.\n\n  c. Copyright and Similar Rights means copyright and/or similar rights\n     closely related to copyright including, without limitation,\n     performance, broadcast, sound recording, and Sui Generis Database\n     Rights, without regard to how the rights are labeled or\n     categorized. For purposes of this Public License, the rights\n     specified in Section 2(b)(1)-(2) are not Copyright and Similar\n     Rights.\n\n  d. Effective Technological Measures means those measures that, in the\n     absence of proper authority, may not be circumvented under laws\n     fulfilling obligations under Article 11 of the WIPO Copyright\n     Treaty adopted on December 20, 1996, and/or similar international\n     agreements.\n\n  e. Exceptions and Limitations means fair use, fair dealing, and/or\n     any other exception or limitation to Copyright and Similar Rights\n     that applies to Your use of the Licensed Material.\n\n  f. Licensed Material means the artistic or literary work, database,\n     or other material to which the Licensor applied this Public\n     License.\n\n  g. Licensed Rights means the rights granted to You subject to the\n     terms and conditions of this Public License, which are limited to\n     all Copyright and Similar Rights that apply to Your use of the\n     Licensed Material and that the Licensor has authority to license.\n\n  h. Licensor means the individual(s) or entity(ies) granting rights\n     under this Public License.\n\n  i. Share means to provide material to the public by any means or\n     process that requires permission under the Licensed Rights, such\n     as reproduction, public display, public performance, distribution,\n     dissemination, communication, or importation, and to make material\n     available to the public including in ways that members of the\n     public may access the material from a place and at a time\n     individually chosen by them.\n\n  j. Sui Generis Database Rights means rights other than copyright\n     resulting from Directive 96/9/EC of the European Parliament and of\n     the Council of 11 March 1996 on the legal protection of databases,\n     as amended and/or succeeded, as well as other essentially\n     equivalent rights anywhere in the world.\n\n  k. You means the individual or entity exercising the Licensed Rights\n     under this Public License. Your has a corresponding meaning.\n\n\nSection 2 -- Scope.\n\n  a. License grant.\n\n       1. Subject to the terms and conditions of this Public License,\n          the Licensor hereby grants You a worldwide, royalty-free,\n          non-sublicensable, non-exclusive, irrevocable license to\n          exercise the Licensed Rights in the Licensed Material to:\n\n            a. reproduce and Share the Licensed Material, in whole or\n               in part; and\n\n            b. produce, reproduce, and Share Adapted Material.\n\n       2. Exceptions and Limitations. For the avoidance of doubt, where\n          Exceptions and Limitations apply to Your use, this Public\n          License does not apply, and You do not need to comply with\n          its terms and conditions.\n\n       3. Term. The term of this Public License is specified in Section\n          6(a).\n\n       4. Media and formats; technical modifications allowed. The\n          Licensor authorizes You to exercise the Licensed Rights in\n          all media and formats whether now known or hereafter created,\n          and to make technical modifications necessary to do so. The\n          Licensor waives and/or agrees not to assert any right or\n          authority to forbid You from making technical modifications\n          necessary to exercise the Licensed Rights, including\n          technical modifications necessary to circumvent Effective\n          Technological Measures. For purposes of this Public License,\n          simply making modifications authorized by this Section 2(a)\n          (4) never produces Adapted Material.\n\n       5. Downstream recipients.\n\n            a. Offer from the Licensor -- Licensed Material. Every\n               recipient of the Licensed Material automatically\n               receives an offer from the Licensor to exercise the\n               Licensed Rights under the terms and conditions of this\n               Public License.\n\n            b. No downstream restrictions. You may not offer or impose\n               any additional or different terms or conditions on, or\n               apply any Effective Technological Measures to, the\n               Licensed Material if doing so restricts exercise of the\n               Licensed Rights by any recipient of the Licensed\n               Material.\n\n       6. No endorsement. Nothing in this Public License constitutes or\n          may be construed as permission to assert or imply that You\n          are, or that Your use of the Licensed Material is, connected\n          with, or sponsored, endorsed, or granted official status by,\n          the Licensor or others designated to receive attribution as\n          provided in Section 3(a)(1)(A)(i).\n\n  b. Other rights.\n\n       1. Moral rights, such as the right of integrity, are not\n          licensed under this Public License, nor are publicity,\n          privacy, and/or other similar personality rights; however, to\n          the extent possible, the Licensor waives and/or agrees not to\n          assert any such rights held by the Licensor to the limited\n          extent necessary to allow You to exercise the Licensed\n          Rights, but not otherwise.\n\n       2. Patent and trademark rights are not licensed under this\n          Public License.\n\n       3. To the extent possible, the Licensor waives any right to\n          collect royalties from You for the exercise of the Licensed\n          Rights, whether directly or through a collecting society\n          under any voluntary or waivable statutory or compulsory\n          licensing scheme. In all other cases the Licensor expressly\n          reserves any right to collect such royalties.\n\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n  a. Attribution.\n\n       1. If You Share the Licensed Material (including in modified\n          form), You must:\n\n            a. retain the following if it is supplied by the Licensor\n               with the Licensed Material:\n\n                 i. identification of the creator(s) of the Licensed\n                    Material and any others designated to receive\n                    attribution, in any reasonable manner requested by\n                    the Licensor (including by pseudonym if\n                    designated);\n\n                ii. a copyright notice;\n\n               iii. a notice that refers to this Public License;\n\n                iv. a notice that refers to the disclaimer of\n                    warranties;\n\n                 v. a URI or hyperlink to the Licensed Material to the\n                    extent reasonably practicable;\n\n            b. indicate if You modified the Licensed Material and\n               retain an indication of any previous modifications; and\n\n            c. indicate the Licensed Material is licensed under this\n               Public License, and include the text of, or the URI or\n               hyperlink to, this Public License.\n\n       2. You may satisfy the conditions in Section 3(a)(1) in any\n          reasonable manner based on the medium, means, and context in\n          which You Share the Licensed Material. For example, it may be\n          reasonable to satisfy the conditions by providing a URI or\n          hyperlink to a resource that includes the required\n          information.\n\n       3. If requested by the Licensor, You must remove any of the\n          information required by Section 3(a)(1)(A) to the extent\n          reasonably practicable.\n\n       4. If You Share Adapted Material You produce, the Adapter's\n          License You apply must not prevent recipients of the Adapted\n          Material from complying with this Public License.\n\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n  a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n     to extract, reuse, reproduce, and Share all or a substantial\n     portion of the contents of the database;\n\n  b. if You include all or a substantial portion of the database\n     contents in a database in which You have Sui Generis Database\n     Rights, then the database in which You have Sui Generis Database\n     Rights (but not its individual contents) is Adapted Material; and\n\n  c. You must comply with the conditions in Section 3(a) if You Share\n     all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not\nreplace Your obligations under this Public License where the Licensed\nRights include other Copyright and Similar Rights.\n\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n  c. The disclaimer of warranties and limitation of liability provided\n     above shall be interpreted in a manner that, to the extent\n     possible, most closely approximates an absolute disclaimer and\n     waiver of all liability.\n\n\nSection 6 -- Term and Termination.\n\n  a. This Public License applies for the term of the Copyright and\n     Similar Rights licensed here. However, if You fail to comply with\n     this Public License, then Your rights under this Public License\n     terminate automatically.\n\n  b. Where Your right to use the Licensed Material has terminated under\n     Section 6(a), it reinstates:\n\n       1. automatically as of the date the violation is cured, provided\n          it is cured within 30 days of Your discovery of the\n          violation; or\n\n       2. upon express reinstatement by the Licensor.\n\n     For the avoidance of doubt, this Section 6(b) does not affect any\n     right the Licensor may have to seek remedies for Your violations\n     of this Public License.\n\n  c. For the avoidance of doubt, the Licensor may also offer the\n     Licensed Material under separate terms or conditions or stop\n     distributing the Licensed Material at any time; however, doing so\n     will not terminate this Public License.\n\n  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n     License.\n\n\nSection 7 -- Other Terms and Conditions.\n\n  a. The Licensor shall not be bound by any additional or different\n     terms or conditions communicated by You unless expressly agreed.\n\n  b. Any arrangements, understandings, or agreements regarding the\n     Licensed Material not stated herein are separate from and\n     independent of the terms and conditions of this Public License.\n\n\nSection 8 -- Interpretation.\n\n  a. For the avoidance of doubt, this Public License does not, and\n     shall not be interpreted to, reduce, limit, restrict, or impose\n     conditions on any use of the Licensed Material that could lawfully\n     be made without permission under this Public License.\n\n  b. To the extent possible, if any provision of this Public License is\n     deemed unenforceable, it shall be automatically reformed to the\n     minimum extent necessary to make it enforceable. If the provision\n     cannot be reformed, it shall be severed from this Public License\n     without affecting the enforceability of the remaining terms and\n     conditions.\n\n  c. No term or condition of this Public License will be waived and no\n     failure to comply consented to unless expressly agreed to by the\n     Licensor.\n\n  d. Nothing in this Public License constitutes or may be interpreted\n     as a limitation upon, or waiver of, any privileges and immunities\n     that apply to the Licensor or You, including from the legal\n     processes of any jurisdiction or authority.\n\n\n=======================================================================\n\nCreative Commons is not a party to its public licenses.\nNotwithstanding, Creative Commons may elect to apply one of its public\nlicenses to material it publishes and in those instances will be\nconsidered the \"Licensor.\" Except for the limited purpose of indicating\nthat material is shared under a Creative Commons public license or as\notherwise permitted by the Creative Commons policies published at\ncreativecommons.org/policies, Creative Commons does not authorize the\nuse of the trademark \"Creative Commons\" or any other trademark or logo\nof Creative Commons without its prior written consent including,\nwithout limitation, in connection with any unauthorized modifications\nto any of its public licenses or any other arrangements,\nunderstandings, or agreements concerning use of licensed material. For\nthe avoidance of doubt, this paragraph does not form part of the public\nlicenses.\n\nCreative Commons may be contacted at creativecommons.org.\n"
  },
  {
    "path": "READINGS.md",
    "content": "# Related Links\n- [React in Patterns by krasimir](https://github.com/krasimir/react-in-patterns)\n- [React Patterns by planningcenter](https://github.com/planningcenter/react-patterns)\n- [reactpatterns.com](https://github.com/chantastic/reactpatterns.com)\n- [10 React Mini-patterns](https://hackernoon.com/10-react-mini-patterns-c1da92f068c5)"
  },
  {
    "path": "README.md",
    "content": "# [React Bits](https://vasanthk.gitbooks.io/react-bits)\n\nA compilation of React Patterns, techniques, tips and tricks.\n\n**Gitbook format**: https://vasanthk.gitbooks.io/react-bits\n\n**Github repo**: https://github.com/vasanthk/react-bits\n\n> Your contributions are heartily ♡ welcome. (✿◠‿◠)\n\n> **Translations by community:**\n> - 中文版 (Chinese): [react-bits-cn](https://github.com/hateonion/react-bits-CN)\n> - 한국어 (Korean): [react-bits-ko](https://github.com/rayleighko/react-bits-ko)\n\n\n- Design Patterns and Techniques\n  - [Conditional in JSX](./patterns/1.conditionals-in-jsx.md)\n  - [Async Nature Of setState()](./patterns/2.async-nature-of-setState.md)\n  - [Dependency Injection](./patterns/3.dependency-injection.md)\n  - [Context Wrapper](./patterns/4.context-wrapper.md)\n  - [Event Handlers](./patterns/5.event-handlers.md)\n  - [Flux Pattern](./patterns/6.flux-pattern.md)\n  - [One Way Data Flow](./patterns/7.one-way-data-flow.md)\n  - [Presentational vs Container](./patterns/8.presentational-vs-container.md)\n  - [Third Party Integration](./patterns/9.third-party-integration.md)\n  - [Passing Function To setState()](./patterns/10.passing-function-to-setState.md)\n  - [Decorators](./patterns/11.decorators.md)\n  - [Feature Flags](./patterns/12.feature-flags-using-redux.md)\n  - [Component Switch](./patterns/13.component-switch.md)\n  - [Reaching Into A Component](./patterns/14.reaching-into-a-component.md)\n  - [List Components](./patterns/15.list-components.md)\n  - [Format Text via Component](./patterns/16.format-text-via-component.md)\n  - [React Fragments](./patterns/17.react-fragments.md)\n  - [Share Tracking Logic](./patterns/18.share-tracking-logic.md)\n- Anti-Patterns\n  - [Introduction](./anti-patterns/README.md)\n  - [Props In Initial State](./anti-patterns/01.props-in-initial-state.md)\n  - [findDOMNode()](./anti-patterns/02.findDOMNode.md)\n  - [Mixins](./anti-patterns/03.mixins.md)\n  - [setState() in componentWillMount()](./anti-patterns/04.setState-in-componentWillMount.md)\n  - [Mutating State](./anti-patterns/05.mutating-state.md)\n  - [Using Indexes as Key](./anti-patterns/06.using-indexes-as-key.md)\n  - [Spreading Props on DOM elements](./anti-patterns/07.spreading-props-dom.md)\n- Handling UX Variations\n  - [Introduction](./ux-variations/README.md)\n  - [Composing UX Variations](./ux-variations/01.composing-variations.md)\n  - [Toggle UI Elements](./ux-variations/02.toggle-ui-elements.md)\n  - [HOC for Feature Toggles](./ux-variations/03.HOC-feature-toggles.md)\n  - [HOC props proxy](./ux-variations/04.HOC-props-proxy.md)\n  - [Wrapper Components](./ux-variations/05.wrapper-components.md)\n  - [Display Order Variations](./ux-variations/06.display-order-variations.md)\n- Perf Tips\n  - [Introduction](./perf-tips/README.md)\n  - [shouldComponentUpdate() check](./perf-tips/01.shouldComponentUpdate-check.md)\n  - [Using Pure Components](./perf-tips/02.pure-component.md)\n  - [Using reselect](./perf-tips/03.reselect.md)\n- Styling\n  - [Introduction](./styling/README.md)\n  - [Stateless UI Components](./styling/01.stateless-ui-components.md)\n  - [Styles Module](./styling/02.styles-module.md)\n  - [Style Functions](./styling/03.style-functions.md)\n  - [NPM Modules](./styling/04.using-npm-modules.md)\n  - [Base Component](./styling/05.base-component.md)\n  - [Layout Component](./styling/06.layout-component.md)\n  - [Typography Component](./styling/07.typography-component.md)\n  - [HOC for Styling](./styling/08.HOC-for-styling.md)\n- Gotchas\n  - [Introduction](./gotchas/README.md)\n  - [Pure render checks](./gotchas/01.pure-render-checks.md)\n  - [Synthetic Events](./gotchas/02.synthetic-events.md)\n- [Related Links](./READINGS.md)\n"
  },
  {
    "path": "SUMMARY.md",
    "content": "# React Bits\n✨ React patterns, techniques, tips and tricks ✨\n\n- Design Patterns and Techniques\n  - [Conditional in JSX](./patterns/18.conditionals-in-jsx.md)\n  - [Async Nature Of setState()](./patterns/19.async-nature-of-setState.md)\n  - [Dependency Injection](./patterns/20.dependency-injection.md)\n  - [Context Wrapper](./patterns/21.context-wrapper.md)\n  - [Event Handlers](./patterns/22.event-handlers.md)\n  - [Flux Pattern](./patterns/23.flux-pattern.md)\n  - [One Way Data Flow](./patterns/24.one-way-data-flow.md)\n  - [Presentational vs Container](./patterns/25.presentational-vs-container.md)\n  - [Third Party Integration](./patterns/26.third-party-integration.md)\n  - [Passing Function To setState()](./patterns/27.passing-function-to-setState.md)\n  - [Decorators](./patterns/28.decorators.md)\n  - [Feature Flags](./patterns/29.feature-flags-using-redux.md)\n  - [Component Switch](./patterns/30.component-switch.md)\n  - [Reaching Into A Component](./patterns/31.reaching-into-a-component.md)\n  - [List Components](./patterns/32.list-components.md)\n  - [Format Text via Component](./patterns/33.format-text-via-component.md)\n  - [Share Tracking Logic](./patterns/34.share-tracking-logic.md)\n- Anti-Patterns\n  - [Introduction](./anti-patterns/README.md)\n  - [Props In Initial State](./anti-patterns/01.props-in-initial-state.md)\n  - [findDOMNode()](./anti-patterns/02.findDOMNode.md)\n  - [Mixins](./anti-patterns/03.mixins.md)\n  - [setState() in componentWillMount()](./anti-patterns/04.setState-in-componentWillMount.md)\n  - [Mutating State](./anti-patterns/05.mutating-state.md)\n  - [Using Indexes as Key](./anti-patterns/06.using-indexes-as-key.md)\n  - [Spreading Props on DOM elements](./anti-patterns/07.spreading-props-dom.md)\n- Handling UX Variations\n  - [Introduction](./ux-variations/README.md)\n  - [Composing UX Variations](./ux-variations/01.composing-variations.md)\n  - [Toggle UI Elements](./ux-variations/02.toggle-ui-elements.md)\n  - [HOC for Feature Toggles](./ux-variations/03.HOC-feature-toggles.md)\n  - [HOC props proxy](./ux-variations/04.HOC-props-proxy.md)\n  - [Wrapper Components](./ux-variations/05.wrapper-components.md)\n  - [Display Order Variations](./ux-variations/06.display-order-variations.md)\n- Perf Tips\n  - [Introduction](./perf-tips/README.md)\n  - [shouldComponentUpdate() check](./perf-tips/01.shouldComponentUpdate-check.md)\n  - [Using Pure Components](./perf-tips/02.pure-component.md)\n  - [Using reselect](./perf-tips/03.reselect.md)\n- Styling\n  - [Introduction](./styling/README.md)\n  - [Stateless UI Components](./styling/01.stateless-ui-components.md)\n  - [Styles Module](./styling/02.styles-module.md)\n  - [Style Functions](./styling/03.style-functions.md)\n  - [npm Modules](./styling/04.using-npm-modules.md)\n  - [Base Component](./styling/05.base-component.md)\n  - [Layout Component](./styling/06.layout-component.md)\n  - [Typography Component](./styling/07.typography-component.md)\n  - [HOC for Styling](./styling/08.HOC-for-styling.md)\n- Gotchas\n  - [Introduction](./gotchas/README.md)\n  - [Pure render checks](./gotchas/01.pure-render-checks.md)\n  - [Synthetic Events](./gotchas/02.synthetic-events.md)\n- [Related Links](./READINGS.md)\n"
  },
  {
    "path": "anti-patterns/01.props-in-initial-state.md",
    "content": "# Props in Initial State\nFrom docs:\n> Using props to generate state in getInitialState often leads to duplication of “source of truth”, i.e. where the real data is.\n> This is because getInitialState is only invoked when the component is first created.\n\nThe danger is that if the props on the component are changed without the component being ‘refreshed’,\nthe new prop value will never be displayed because the constructor function (or getInitialState) will never update the current state of the component.\nThe initialization of state from props only runs when the component is first created.\n\n#### Bad\n```javascript\nclass SampleComponent extends Component {\n  // constructor function (or getInitialState)\n  constructor(props) {\n    super(props);\n    this.state = {\n      flag: false,\n      inputVal: props.inputValue\n    };\n  }\n\n  render() {\n    return <div>{this.state.inputVal && <AnotherComponent/>}</div>\n  }\n}\n```\n#### Good\n```javascript\nclass SampleComponent extends Component {\n  // constructor function (or getInitialState)\n  constructor(props) {\n    super(props);\n    this.state = {\n      flag: false\n    };\n  }\n\n  render() {\n    return <div>{this.props.inputValue && <AnotherComponent/>}</div>\n  }\n}\n```\n\n### Related links:\n - [React Anti-Patterns: Props in Initial State](https://medium.com/@justintulk/react-anti-patterns-props-in-initial-state-28687846cc2e)\n - [Why is passing the component initial state a prop an anti-pattern?](http://stackoverflow.com/questions/28785106/reactjs-why-is-passing-the-component-initial-state-a-prop-an-anti-pattern)\n"
  },
  {
    "path": "anti-patterns/02.findDOMNode.md",
    "content": "# Refs over findDOMNode()\nUse callback refs over findDOMNode()\n\nNote:\nReact also supports using a string (instead of a callback) as a ref prop on any component, although this approach is mostly legacy at this point.\n- [More about refs](https://reactjs.org/docs/refs-and-the-dom.html)\n- [Why ref-string is legacy?](http://stackoverflow.com/questions/37468913/why-ref-string-is-legacy)\n\n##### findDOMNode(this)\n\n###### Before:\n```javascript\nclass MyComponent extends Component {\n  componentDidMount() {\n    findDOMNode(this).scrollIntoView();\n  }\n\n  render() {\n    return <div />\n  }\n}\n```\n###### After\n```javascript\nclass MyComponent extends Component {\n  componentDidMount() {\n    this.node.scrollIntoView();\n  }\n\n  render() {\n    return <div ref={node => this.node = node}/>\n  }\n}\n```\n##### findDOMNode(stringDOMRef)\n###### Before\n```javascript\nclass MyComponent extends Component {\n  componentDidMount() {\n    findDOMNode(this.refs.something).scrollIntoView();\n  }\n\n  render() {\n    return (\n      <div>\n        <div ref='something'/>\n      </div>\n    )\n  }\n}\n```\n###### After\n```javascript\nclass MyComponent extends Component {\n  componentDidMount() {\n    this.something.scrollIntoView();\n  }\n\n  render() {\n    return (\n      <div>\n        <div ref={node => this.something = node}/>\n      </div>\n    )\n  }\n}\n```\n##### findDOMNode(childComponentStringRef)\n###### Before:\n```javascript\nclass Field extends Component {\n  render() {\n    return <input type='text'/>\n  }\n}\n\nclass MyComponent extends Component {\n  componentDidMount() {\n    findDOMNode(this.refs.myInput).focus();\n  }\n\n  render() {\n    return (\n      <div>\n        Hello,\n        <Field ref='myInput'/>\n      </div>\n    )\n  }\n}\n```\n###### After\n```javascript\nclass Field extends Component {\n  render() {\n    return (\n      <input type='text' ref={this.props.inputRef}/>\n    )\n  }\n}\n\nclass MyComponent extends Component {\n  componentDidMount() {\n    this.inputNode.focus();\n  }\n\n  render() {\n    return (\n      <div>\n        Hello,\n        <Field inputRef={node => this.inputNode = node}/>\n      </div>\n    )\n  }\n}\n```\n\n### Related links:\n- [ESLint Rule proposal: warn against using findDOMNode()](https://github.com/yannickcr/eslint-plugin-react/issues/678#issue-165177220)\n- [Refs and the DOM](https://reactjs.org/docs/refs-and-the-dom.html)\n"
  },
  {
    "path": "anti-patterns/03.mixins.md",
    "content": "# Use Higher order components over Mixins\n\n#### Simple Example\n```javascript\n// With Mixin\nvar WithLink = React.createClass({\n  mixins: [React.addons.LinkedStateMixin],\n  getInitialState: function () {\n    return {message: 'Hello!'};\n  },\n  render: function () {\n    return <input type=\"text\" valueLink={this.linkState('message')}/>;\n  }\n});\n\n// Move logic to a HOC\nvar WithLink = React.createClass({\n  getInitialState: function () {\n    return {message: 'Hello!'};\n  },\n  render: function () {\n    return <input type=\"text\" valueLink={LinkState(this,'message')}/>;\n  }\n});\n```\n\n#### Detailed Example\n\n```javascript\n// With Mixin\nvar CarDataMixin = {\n  componentDidMount: {\n    // fetch car data and\n    // call this.setState({carData: fetchedData}),\n    // once data has been (asynchronously) fetched\n  }\n};\n\nvar FirstView = React.createClass({\n  mixins: [CarDataMixin],\n  render: function () {\n    return (\n      <div>\n        <AvgSellingPricesByYear country=\"US\" dataset={this.state.carData}/>\n        <AvgSellingPricesByYear country=\"UK\" dataset={this.state.carData}/>\n        <AvgSellingPricesByYear country=\"FI\" dataset={this.state.carData}/>\n      </div>\n    )\n  }\n});\n\n// With HOC\nvar bindToCarData = function (Component) {\n  return React.createClass({\n    componentDidMount: {\n      // fetch car data and\n      // call this.setState({carData: fetchedData}),\n      // once data has been (asynchronously) fetched\n    },\n\n    render: function () {\n      return <Component carData={ this.state.carData }/>\n    }\n  });\n};\n\n// Then wrap your component when you define it.\nvar FirstView = bindToCarData(React.createClass({\n  render: function () {\n    return (\n      <div>\n        <AvgSellingPricesByYear country=\"US\" dataset={this.props.carData}/>\n        <AvgSellingPricesByYear country=\"UK\" dataset={this.props.carData}/>\n        <AvgSellingPricesByYear country=\"FI\" dataset={this.props.carData}/>\n      </div>\n    )\n  }\n}));\n```\n\n### Related links:\n- [Mixins are dead - Long live higher ordercomponents](https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750)\n- [Mixins are considered harmful](https://reactjs.org/blog/2016/07/13/mixins-considered-harmful.html)\n- [Stackoverflow: Using mixins vs components for code reuse](http://stackoverflow.com/questions/21854938/using-mixins-vs-components-for-code-reuse-in-facebook-react)\n- [Stackoverflow: Composition instead of mixins in React](http://stackoverflow.com/questions/30845561/how-to-solve-this-using-composition-instead-of-mixins-in-react)\n"
  },
  {
    "path": "anti-patterns/04.setState-in-componentWillMount.md",
    "content": "# setState() in componentWillMount()\nAvoid async initialization in ``componentWillMount()``\n\n``componentWillMount()`` is invoked immediately before mounting occurs.\nIt is called before ``render()``, therefore setting state in this method will not trigger a re-render.\nAvoid introducing any side-effects or subscriptions in this method.\n\n\nMake async calls for component initialization in ``componentDidMount`` instead of ``componentWillMount``\n```javascript\nfunction componentDidMount() {\n  axios.get(`api/messages`)\n    .then((result) => {\n      const messages = result.data\n      console.log(\"COMPONENT WILL Mount messages : \", messages);\n      this.setState({\n        messages: [...messages.content]\n      })\n    })\n}\n```\n"
  },
  {
    "path": "anti-patterns/05.mutating-state.md",
    "content": "# Mutating State without setState()\n- Causes state changes without making component re-render.\n- Whenever setState gets called in future, the mutated state gets applied.\n\n#### Bad\n``` javascript\nclass SampleComponent extends Component {\n  constructor(props) {\n    super(props);\n\n    this.state = {\n      items: ['foo', 'bar']\n    };\n\n    this.handleClick = this.handleClick.bind(this);\n  }\n\n  handleClick() {\n    // BAD: We mutate state here\n    this.state.items.push('lorem');\n\n    this.setState({\n      items: this.state.items\n    });\n  }\n\n  render() {\n    return (\n      <div>\n        {this.state.items.length}\n        <button onClick={this.handleClick}>+</button>\n      </div>\n    )\n  }\n}\n```\n\n#### Good\n``` javascript\nclass SampleComponent extends Component {\n  constructor(props) {\n    super(props);\n\n    this.state = {\n      items: ['foo', 'bar']\n    };\n\n    this.handleClick = this.handleClick.bind(this);\n  }\n\n  handleClick() {\n    // We update using setState() - concat return new array after appending new item.\n    this.setState(prevState => ({\n      items: prevState.items.concat('lorem')\n    }));\n  }\n\n  render() {\n    return (\n      <div>\n        {this.state.items.length}\n        <button onClick={this.handleClick}>+</button>\n      </div>\n    )\n  }\n}\n```\n\n### Related links:\n[React Design Patterns and best practices by Michele Bertoli.](https://github.com/MicheleBertoli/react-design-patterns-and-best-practices)\n"
  },
  {
    "path": "anti-patterns/06.using-indexes-as-key.md",
    "content": "# Using indexes as keys\nKeys should be stable, predictable, and unique so that React can keep track of elements.\n\n#### Bad\nIn this snippet each element's key will be based on ordering, rather than tied to the data that is being represented. This limits the optimizations that React can do.\n```javascript\n{todos.map((todo, index) =>\n  <Todo\n    {...todo}\n    key={index}\n  />\n)}\n```\n\n#### Good\nAssuming `todo.id` is unique to this list and stable, React would be able to reorder elements without needing to reevaluate them as much.\n```javascript\n{todos.map((todo) =>\n  <Todo {...todo}\n    key={todo.id} />\n)}\n```\n\n### @Reference:\n- [React docs](https://reactjs.org/docs/reconciliation.html#tradeoffs)\n- [Lin Clark's code cartoon](https://youtu.be/-t8eOoRsJ7M?t=981)\n"
  },
  {
    "path": "anti-patterns/07.spreading-props-dom.md",
    "content": "# Spreading props on DOM elements\nWhen we spread props we run into the risk of adding unknown HTML attributes, which is a bad practice.\n\n#### Bad\nThis will try to add the unknown HTML attribute `flag` to the DOM element.\n```javascript\nconst Sample = () => (<Spread flag={true} className=\"content\"/>);\nconst Spread = (props) => (<div {...props}>Test</div>);\n```\n#### Good\nBy creating props specifically for DOM attribute, we can safely spread.\n```javascript\nconst Sample = () => (<Spread flag={true} domProps={{className: \"content\"}}/>);\nconst Spread = (props) => (<div {...props.domProps}>Test</div>);\n```\n\nOr alternatively we can use prop destructuring with `...rest`:\n```javascript\nconst Sample = () => (<Spread flag={true} className=\"content\"/>);\nconst Spread = ({ flag, ...domProps }) => (<div {...domProps}>Test</div>);\n```\n\n*Note*\n\nIn [scenarios](https://github.com/vasanthk/react-bits/issues/34) where you use a [PureComponent](../perf-tips/02.pure-component.md), when an update happens it re-renders the component even if `domProps` did not change. This is because PureComponent only [shallowly compares](https://reactjs.org/docs/react-api.html#reactpurecomponent) the objects.\n\n### Related links:\n- [React Design Patterns and best practices by Michele Bertoli.](https://github.com/MicheleBertoli/react-design-patterns-and-best-practices)\n- [In React, children are just props: Kent C. Dodds' Tweet](https://twitter.com/kentcdodds/status/851406788549369856)\n"
  },
  {
    "path": "anti-patterns/README.md",
    "content": "# Anti-patterns\n\nFamiliarizing ourselves with common anti-patterns will help us understand how React works and describe useful forms of refactoring our code.\n"
  },
  {
    "path": "book.json",
    "content": "{\n  \"gitbook\": \">3.0.0\",\n  \"plugins\": [\"edit-link\"],\n  \"pluginsConfig\": {\n    \"edit-link\": {\n      \"base\": \"https://github.com/vasanthk/react-bits/blob/master\",\n      \"label\": \"Edit This Page\"\n    },\n    \"github\": {\n      \"url\": \"https://github.com/vasanthk/react-bits/\"\n    }\n  }\n}\n"
  },
  {
    "path": "coding-style/README.md",
    "content": "# Coding Style\n\n**Disclaimer:**\n\nThis section is purely to familiarize oneself with different coding styles out there. It is not a set of coding standards or conventions!\n"
  },
  {
    "path": "gotchas/01.pure-render-checks.md",
    "content": "# Pure Render Checks\n\nIn order to preserve performance one needs to consider the creation of new entities in the render method.\n\nPure render?\n\nWith React.js pure render I mean components that implement the shouldComponentUpdate method with shallow equality checks.\n\nExamples of this are the React.PureComponent, PureRenderMixin, recompose/pure and many others.\n\n#### Case 1\n\n##### Bad\n```javascript\nclass Table extends PureComponent {\n  render() {\n    return (\n      <div>\n        {this.props.items.map(i =>\n          <Cell data={i} options={this.props.options || []}/>\n        )}\n      </div>\n    );\n  }\n}\n```\n\n**The issue is with ``{this.props.options || []}`` - it caused all the cells to be re-rendered even for a single cell change. Why?**\n\nYou see the options array was passed deep down in the Cell elements. Normally this would not be an issue.\nThe other Cell elements would not be re-rendered because they can do the cheap shallow equality check and\nskip the render entirely but in this case the options prop was null and the default array was used.\nAs you should know the array literal is the same as new Array() which creates a new array instance.\nThis completely destroyed every pure render optimization inside the Cell elements.\nIn Javascript different instances have different identities and thus the shallow equality check always\nproduces false and tells React to re-render the components.\n\n##### Good\n```javascript\nconst defaultval = [];  // <---  The fix (defaultProps could also have been used).\nclass Table extends PureComponent {\n  render() {\n    return (\n      <div>\n        {this.props.items.map(i =>\n          <Cell data={i} options={this.props.options || defaultval}/>\n        )}\n      </div>\n    );\n  }\n}\n```\n#### Case 2\nSimilar issue with using functions in render() as well\n\n##### BAD\n```javascript\nclass App extends PureComponent {\n  render() {\n    return <MyInput\n      onChange={e => this.props.update(e.target.value)}/>;\n  }\n}\n```\n##### Bad again\n```javascript\nclass App extends PureComponent {\n  update(e) {\n    this.props.update(e.target.value);\n  }\n\n  render() {\n    return <MyInput onChange={this.update.bind(this)}/>;\n  }\n}\n```\n^^In both cases a new function is created with a new identity. Just like with the array literal.\nWe need to bind the function early\n\n##### Good\n```javascript\nclass App extends PureComponent {\n  constructor(props) {\n    super(props);\n    this.update = this.update.bind(this);\n  }\n\n  update(e) {\n    this.props.update(e.target.value);\n  }\n\n  render() {\n    return <MyInput onChange={this.update}/>;\n  }\n}\n```\n##### Bad\n```javascript\nclass Component extends React.Component {\n  state = {clicked: false};\n\n  onClick() {\n    this.setState({clicked: true})\n  }\n\n  render() {\n    // Options object created each render if not set\n    const options = this.props.options || {test: 1};\n\n    return <Something\n      options={options}\n      // New function created each render\n      onClick={this.onClick.bind(this)}\n      // New function & closure created each render\n      onTouchTap={(event) => this.onClick(event)\n    />\n  }\n}\n```\n##### Good\n```javascript\nclass Component extends React.Component {\n  state = {clicked: false};\n  options = {test: 1};\n\n  onClick = () => {\n    this.setState({clicked: true})\n  };\n\n  render() {\n    // Options object created once\n    const options = this.props.options || this.options;\n\n    return <Something\n      options={options}\n      onClick={this.onClick} // Function created once, bound once\n      onTouchTap={this.onClick} // Function created once, bound once\n    />\n  }\n}\n```\n\n### Related links:\n- https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f\n- https://github.com/nfour/js-structures/blob/master/guides/react-anti-patterns.md#pure-render-immutability\n- [Optimizing React Rendering](https://flexport.engineering/optimizing-react-rendering-part-1-9634469dca02)\n"
  },
  {
    "path": "gotchas/02.synthetic-events.md",
    "content": "# Synthetic events in React\nInside React event handlers, the event object is wrapped in a SyntheticEvent object.\nThese objects are pooled, which means that the objects received at an event handler will be reused for other events to increase performance.\nThis also means that accessing the event object’s properties asynchronously will be impossible since the event’s properties have been reset due to reuse.\n\nThe following piece of code will log null because event has been reused inside the SyntheticEvent pool:\n```javascript\nfunction handleClick(event) {\n  setTimeout(function () {\n    console.log(event.target.name);\n  }, 1000);\n}\n```\nTo avoid this you need to store the event’s property you are interested in inside its own binding:\n```javascript\nfunction handleClick(event) {\n  let name = event.target.name;\n  setTimeout(function () {\n    console.log(name);\n  }, 1000);\n}\n```\n\n### Related links:\n- [React/Redux: Best practices & gotchas](https://medium.com/nick-parsons/react-redux-best-practices-gotchas-56cf61c1c415)\n- [React events in depth w/ Kent C. Dodds, Ben Alpert, & Dan Abramov](https://www.youtube.com/watch?v=dRo_egw7tBc)"
  },
  {
    "path": "gotchas/README.md",
    "content": "# Gotchas\n\nReact is intuitive for the most part, but there are quite a few stumbling points which might catch you by surprise. We'll discuss more on them here.\n\n## Articles\n\n[React Gotchas](https://daveceddia.com/react-gotchas/)\n\n[Top 5 React Gotchas](http://joelgriffith.net/top-5-react-gotchas/)"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"react-bits\",\n  \"version\": \"1.0.0\",\n  \"repository\": \"https://github.com/vasanthk/react-bits.git\",\n  \"author\": \"\",\n  \"license\": \"MIT\",\n  \"scripts\": {\n    \"docs\": \"gitbook serve\"\n  }\n}\n"
  },
  {
    "path": "patterns/1.conditionals-in-jsx.md",
    "content": "# Conditionals in JSX\n\nInstead of\n```javascript\nconst sampleComponent = () => {\n  return isTrue ? <p>True!</p> : null\n};\n```\n\nUse short-circuit evaluation\n```javascript\nconst sampleComponent = () => {\n  return isTrue && <p>True!</p>\n};\n```\nFor Complex scenarios with too many ternaries:\n\n```javascript\n// Y soo many ternary??? :-/\nconst sampleComponent = () => {\n  return (\n    <div>\n      {flag && flag2 && !flag3\n        ? flag4\n        ? <p>Blah</p>\n        : flag5\n        ? <p>Meh</p>\n        : <p>Herp</p>\n        : <p>Derp</p>\n      }\n    </div>\n  )\n};\n```\n\n - Best approach: Move logic to sub-components\n - Alternate hacky approach: Use IIFE\n\nThere are some libraries that solve this problem (JSX-Control Statements), but rather than introduce another dependency\nuse an [IIFE](http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) and return values by using if-else statement inside\n\n```javascript\nconst sampleComponent = () => {\n  return (\n    <div>\n      {\n        (() => {\n          if (flag && flag2 && !flag3) {\n            if (flag4) {\n              return <p>Blah</p>\n            } else if (flag5) {\n              return <p>Meh</p>\n            } else {\n              return <p>Herp</p>\n            }\n          } else {\n            return <p>Derp</p>\n          }\n        })()\n      }\n    </div>\n  )\n};\n```\n\n\nWith an appropiate [transpiler](https://babeljs.io/docs/plugins/transform-do-expressions/) you can take advantage of the upcoming [do expression](https://github.com/tc39/proposal-do-expressions) which is currently on [stage-1](https://github.com/tc39/proposal-do-expressions)\n\n\n```javascript\nconst sampleComponent = () => {\n  return (\n    <div>\n      {\n        do {\n          if (flag && flag2 && !flag3) {\n            if (flag4) {\n              return <p>Blah</p>;\n            } else if (flag5) {\n              return <p>Meh</p>;\n            } else {\n              return <p>Herp</p>;\n            }\n          } else {\n            return <p>Derp</p>;\n          }\n        }\n      }\n    </div>\n  )\n};\n```\n\n\nOr alternatively simply use early returns\n\n```javascript\nconst sampleComponent = () => {\n  const basicCondition = flag && flag2 && !flag3;\n  if (!basicCondition) return <p>Derp</p>;\n  if (flag4) return <p>Blah</p>;\n  if (flag5) return <p>Meh</p>;\n  return <p>Herp</p>\n}\n```\n\n### Related links:\n- https://engineering.musefind.com/our-best-practices-for-writing-react-components-dec3eb5c3fc8\n- [Conditional rendering](https://reactjs.org/docs/conditional-rendering.html)\n\n\n"
  },
  {
    "path": "patterns/10.passing-function-to-setState.md",
    "content": "# Passing a function to setState\n\nHere’s the dirty secret about setState — it’s actually asynchronous.\nReact batches state changes for performance reasons, so the state may not change immediately after setState is called.\nThat means you should not rely on the current state when calling setState — since you can’t be sure what that state will be!\nHere’s the solution — pass a function to setState, with the previous state as an argument.\nDoing so avoids issues with the user getting the old state value on access (due to the asynchrony of setState)\n\n#### Problem\n```javascript\n// assuming this.state.count === 0\nthis.setState({count: this.state.count + 1});\nthis.setState({count: this.state.count + 1});\nthis.setState({count: this.state.count + 1});\n// this.state.count === 1, not 3\n```\n#### Solution\n```javascript\nthis.setState((prevState, props) => ({\n  count: prevState.count + props.increment\n}));\n```\n\n#### Variations\n```javascript\n// Passing object\nthis.setState({ expanded: !this.state.expanded });\n\n// Passing function\nthis.setState(prevState => ({ expanded: !prevState.expanded }));\n```\n\n### Related links:\n- [setState() Gate](https://medium.com/javascript-scene/setstate-gate-abc10a9b2d82)\n- [Do I need to use setState(function) overload in this case?](http://stackoverflow.com/questions/43428456/do-i-need-to-use-setstatefunction-overload-in-this-case/43440790#43440790)\n- [Functional setState is the future of React](https://medium.freecodecamp.com/functional-setstate-is-the-future-of-react-374f30401b6b)\n"
  },
  {
    "path": "patterns/11.decorators.md",
    "content": "# Decorators\nDecorators (*supported by Babel, in Stage 2 proposal as of 03/17*)\n\nIf you’re using something like mobx, you can decorate your class components — which is the same as passing the component into a function.\nDecorators are flexible and readable way of modifying component functionality.\n\nNon-decorators approach\n```javascript\nclass ProfileContainer extends Component {\n  // Component code\n}\nexport default observer(ProfileContainer)\n```\nWith decorators\n```javascript\n@observer\nexport default class ProfileContainer extends Component {\n  // Component code\n}\n```\n\n### Article:\n- [Enhancing React components with Decorators](https://medium.com/@gigobyte/enhancing-react-components-with-decorators-441320e8606a)\n\n### Related:\n- [Decorators != higher ordered components](https://twitter.com/dan_abramov/status/628202050946514944)\n- [React Decorator example - Module](https://github.com/gigobyte/react-document-title-decorator)\n- [What is the use of Connect(decorator in react-redux)](http://stackoverflow.com/questions/36553814/what-is-the-use-of-connect-decorator-in-react-redux)\n- [Decorators with React Components](http://stackoverflow.com/questions/36286384/decorators-with-react-components)\n- [Exploring ES7 decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841#.8cbzw5wcl)\n- [Understanding Decorators](https://survivejs.com/react/appendices/understanding-decorators/)\n"
  },
  {
    "path": "patterns/12.feature-flags-using-redux.md",
    "content": "# Feature Flags\nEnabling Feature flags in React using Redux\n\n```javascript\n// createFeatureFlaggedContainer.js\nimport React from 'react';\nimport { connect } from 'react-redux';\nimport { isFeatureEnabled } from './reducers'\n\nexport default function createFeatureFlaggedContainer({\n  featureName,\n  enabledComponent,\n  disabledComponent\n  }) {\n  function FeatureFlaggedContainer({ isEnabled, ...props }) {\n    const Component = isEnabled ? enabledComponent : disabledComponent;\n\n    if (Component) {\n      return <Component {...props} />;\n    }\n\n    // `disabledComponent` is optional property\n    return null;\n  }\n\n  // Having `displayName` is very useful for debugging.\n  FeatureFlaggedContainer.displayName = `FeatureFlaggedContainer(${ featureName })`;\n\n  return connect((store) => {\n    isEnabled: isFeatureEnabled(store, featureName)\n  })(FeatureFlaggedContainer);\n}\n```\n```javascript\n// EnabledFeature.js\nimport { connect } from 'react-redux';\nimport { isFeatureEnabled } from './reducers'\n\nfunction EnabledFeature({ isEnabled, children }) {\n  if (isEnabled) {\n    return children;\n  }\n\n  return null;\n}\n\nexport default connect((store, { name }) => {\n  isEnabled: isFeatureEnabled(store, name)\n})(EnabledFeature);\n```\n```javascript\n// featureEnabled.js\nimport createFeatureFlaggedContainer from './createFeatureFlaggedContainer'\n\n// Decorator for \"Page\" components.\n// usage: enabledFeature('unicorns')(UnicornsPage);\nexport default function enabledFeature(featureName) {\n  return (Component) => {\n    return createFeatureFlaggedContainer({\n      featureName,\n      enabledComponent: Component,\n      disabledComponent: PageNotFound, // 404 page or something similar\n    });\n  };\n};\n```\n```javascript\n// features.js\n// This is quite simple reducer, containing only an array of features.\n// You can attach this data to a `currentUser` or similar reducer.\n\n// `BOOTSTAP` is global action, which contains the initial data for a page\n// Features access usually don't change during user usage of a page\nconst BOOTSTAP = 'features/receive';\n\nexport default function featuresReducer(state, { type, payload }) {\n  if (type === BOOTSTAP) {\n    return payload.features || [];\n  }\n\n  return state || [];\n}\n\nexport function isFeatureEnabled(features, featureName) {\n  return features.indexOf(featureName) !== -1;\n}\n```\n```javascript\n// reducers.js\n// This is your main reducer.js file\nimport { combineReducers } from 'redux';\n\nimport features, { isFeatureEnabled as isFeatureEnabledSelector } from './features';\n// ...other reducers\n\nexport default combineReducers({\n  features\n  // ...other reducers\n});\n\n// This is the important part, access to `features` reducer should only happens\n// via this selector.\n// Then you can always change where/how the features are stored.\nexport function isFeatureEnabled({ features }, featureName) {\n  return isFeatureEnabledSelector(features, featureName);\n}\n```\n### Related links:\n - [Feature flags in React](http://blog.rstankov.com/feature-flags-in-react/)\n - [Gist](https://gist.github.com/RStankov/0e764f27daf38f2fcd81b82360334528)\n"
  },
  {
    "path": "patterns/13.component-switch.md",
    "content": "# The switching component\nA switching component is a component that renders one of many components.\n\nUse an object to map prop values to components\n```javascript\nimport HomePage from './HomePage.jsx';\nimport AboutPage from './AboutPage.jsx';\nimport UserPage from './UserPage.jsx';\nimport FourOhFourPage from './FourOhFourPage.jsx';\n\nconst PAGES = {\n  home: HomePage,\n  about: AboutPage,\n  user: UserPage\n};\n\nconst Page = (props) => {\n  const Handler = PAGES[props.page] || FourOhFourPage;\n\n  return <Handler {...props} />\n};\n\n// The keys of the PAGES object can be used in the prop types to catch dev-time errors.\nPage.propTypes = {\n  page: PropTypes.oneOf(Object.keys(PAGES)).isRequired\n};\n```\n\n### Related links:\n - https://hackernoon.com/10-react-mini-patterns-c1da92f068c5\n"
  },
  {
    "path": "patterns/14.reaching-into-a-component.md",
    "content": "# Reaching into a Component\nAccessing a component from the parent.\neg. Autofocus an input (controlled by parent component)\n\n#### Child Component\nAn input component with a focus() method that focuses the HTML element\n```javascript\nclass Input extends Component {\n  focus() {\n    this.el.focus();\n  }\n\n  render() {\n    return (\n      <input\n        ref={el=> { this.el = el; }}\n      />\n    );\n  }\n}\n```\n#### Parent Component\nIn the parent component, we can get a reference to the Input component and call its focus() method.\n```javascript\nclass SignInModal extends Component {\n  componentDidMount() {\n    // Note that when you use ref on a component, it’s a reference to\n    // the component (not the underlying element), so you have access to its methods.\n    this.InputComponent.focus();\n  }\n\n  render() {\n    return (\n      <div>\n        <label>User name:</label>\n        <Input\n          ref={comp => { this.InputComponent = comp; }}\n        />\n      </div>\n    )\n  }\n}\n```\n### Reference:\n- https://hackernoon.com/10-react-mini-patterns-c1da92f068c5\n\n"
  },
  {
    "path": "patterns/15.list-components.md",
    "content": "# Lists Components\nLists and other things that are almost components\n\nInstead of making a separate component for lists I can then generate the results like:\n```javascript\n// renderSearchSuggestion() behaves as a pseudo SearchSuggestion component\n// keep it self contained and it should be easy to extract later if needed\nconst renderSearchSuggestion = listItem => (\n  <li key={listItem.id}>{listItem.name} {listItem.id}</li>\n);\n\nconst SearchSuggestions = (props) => {\n  return (\n    <ul>\n      {props.listItems.map(renderSearchSuggestion)}\n    </ul>\n  );\n};\n```\nIf things get more complex or you want to use this component elsewhere,\nyou should be able to copy/paste the code out into a new component.\nDon’t prematurely componentize.\n\n### Related links:\n- https://hackernoon.com/10-react-mini-patterns-c1da92f068c5\n\n"
  },
  {
    "path": "patterns/16.format-text-via-component.md",
    "content": "# Components for formatting text\nInstead of formatting text by calling helper functions inside render, we can create a separate component that\nhandles this.\n\n#### With Component\nRender function is lot cleaner to comprehend as it is just simple component composition.\n```javascript\nconst Price = (props) => {\n  // toLocaleString is not React specific syntax - it is a native JavaScript function used fo formatting\n  // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString\n  const price = props.children.toLocaleString('en', {\n    style: props.showSymbol ? 'currency' : undefined,\n    currency: props.showSymbol ? 'USD' : undefined,\n    maximumFractionDigits: props.showDecimals ? 2 : 0\n  });\n\n  return <span className={props.className}>{price}</span>\n};\n\nPrice.propTypes = {\n  className: PropTypes.string,\n  children: PropTypes.number,\n  showDecimals: PropTypes.bool,\n  showSymbol: PropTypes.bool\n};\n\nPrice.defaultProps = {\n  children: 0,\n  showDecimals: true,\n  showSymbol: true,\n};\n\nconst Page = () => {\n  const lambPrice = 1234.567;\n  const jetPrice = 999999.99;\n  const bootPrice = 34.567;\n\n  return (\n    <div>\n      <p>One lamb is <Price className=\"expensive\">{lambPrice}</Price></p>\n      <p>One jet is <Price showDecimals={false}>{jetPrice}</Price></p>\n      <p>Those gumboots will set ya back\n        <Price\n        showDecimals={false}\n        showSymbol={false}>\n        {bootPrice}\n        </Price>\n        bucks.\n      </p>\n    </div>\n  );\n};\n```\n#### Without Component\nLess code: But render looks less clean. (Debatable, yeah I understand)\n```javascript\nfunction numberToPrice(num, options = {}) {\n  const showSymbol = options.showSymbol !== false;\n  const showDecimals = options.showDecimals !== false;\n\n  return num.toLocaleString('en', {\n    style: showSymbol ? 'currency' : undefined,\n    currency: showSymbol ? 'USD' : undefined,\n    maximumFractionDigits: showDecimals ? 2 : 0\n  });\n}\n\nconst Page = () => {\n  const lambPrice = 1234.567;\n  const jetPrice = 999999.99;\n  const bootPrice = 34.567;\n\n  return (\n    <div>\n      <p>One lamb is <span className=\"expensive\">{numberToPrice(lambPrice)}</span></p>\n      <p>One jet is {numberToPrice(jetPrice, { showDecimals: false })}</p>\n      <p>Those gumboots will set ya back\n        {numberToPrice(bootPrice, { showDecimals: false, showSymbol: false })}\n        bucks.</p>\n    </div>\n  );\n};\n```\n\n### Reference:\n- [10 React Mini Patterns](https://hackernoon.com/10-react-mini-patterns-c1da92f068c5)\n\n"
  },
  {
    "path": "patterns/17.react-fragments.md",
    "content": "# React Fragments\n\nReact fragments are used whenever a component needs returned with multiple children.\n\nSpecifically, fragments are useful when I don't want to clutter the DOM with unnecessary `<div>` tags that are used purely to wrap children in a React render method.\n\nFor example, React fragments are commonly used to render list items:\n```javascript\nrender() {\n    return (\n      <React.Fragment>\n        <td>Table Cell 1</td>\n        <td>Table Cell 2</td>\n      </React.Fragment>\n    );\n  }\n```\n\nThis solves the issue of breaking the DOM HTML table specifications by not adding unnecessary `<div>` elements around `<td>` elements.\nDo keep in mind, if it is a list being rendered, React does still throw warnings when children don't have the `key={}` prop.\n\n### Related links:\n- https://reactjs.org/docs/fragments.html\n"
  },
  {
    "path": "patterns/18.share-tracking-logic.md",
    "content": "# Share Tracking Logic\nUsing HOC to share tracking logic across various UX components\n\neg. Adding analytics tracking across various components.\n\n- Helps to keep it DRY (Do not Repeat Yourself)\n- Removing tracking logic etc. from the presentational component makes it well testable, which is key.\n\n```javascript\nimport tracker from './tracker.js';\n\n// HOC\nconst pageLoadTracking = (ComposedComponent) => class HOC extends Component {\n  componentDidMount() {\n    tracker.trackPageLoad(this.props.trackingData);\n  }\n\n  componentDidUpdate() {\n    tracker.trackPageLoad(this.props.trackingData);\n  }\n\n  render() {\n    return <ComposedComponent {...this.props} />\n  }\n};\n\n// Usage\nimport LoginComponent from \"./login\";\n\nconst LoginWithTracking = pageLoadTracking(LoginComponent);\n\nclass SampleComponent extends Component {\n  render() {\n    const trackingData = {/** Nested Object **/};\n    return <LoginWithTracking trackingData={trackingData}/>\n  }\n}\n```\n"
  },
  {
    "path": "patterns/2.async-nature-of-setState.md",
    "content": "# Async Nature Of setState()\nOn the Async nature of setState()\n\n## Gist:\nReact batches updates and flushes it out once per frame (perf optimization)\nHowever, in some cases React has no control over batching, hence updates are made synchronously\ne.g. eventListeners, Ajax, setTimeout and similar Web APIs.\n\n\n### Main Idea\nsetState() does not immediately mutate this.state but creates a pending state transition.\nAccessing this.state after calling this method can potentially return the existing value.\nThere is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.\n\n#### Run the below code and you will make the following observations:\n\nYou can see that in every situation (addEventListener, setTimeout or AJAX call) the state before and the state after are different.\nAnd that render was called immediately after triggering the setState method. But why is that?\nWell, it turns out React does not understand and thus cannot control code that doesn't live inside the library.\nTimeouts or AJAX calls for example, are developer authored code that executes outside of the context of React.\n\nSo why does React synchronously update the state in these cases? Well, because it's trying to be as defensive as possible.\nNot being in control means it's not able to do any performance optimisations so it's better to update the state on spot and\nmake sure the code that follows has access to the latest information available.\n\n```javascript\nclass TestComponent extends React.Component {\n  constructor(...args) {\n    super(...args);\n    this.state = {\n      dollars: 10\n    };\n    this._saveButtonRef = (btn => { this._btnRef = btn });\n    [\n      '_onTimeoutHandler',\n      '_onMouseLeaveHandler',\n      '_onClickHandler',\n      '_onAjaxCallback',\n    ].forEach(propToBind => {\n      this[propToBind] = this[propToBind].bind(this);\n    });\n  }\n\n  componentDidMount() {\n    // Add custom event via `addEventListener`\n    //\n    // The list of supported React events does include `mouseleave`\n    // via `onMouseLeave` prop\n    //\n    // However, we are not adding the event the `React way` - this will have\n    // effects on how state mutates\n    //\n    // Check the list here - https://reactjs.org/docs/events.html\n    this._btnRef.addEventListener('mouseleave', this._onMouseLeaveHandler);\n\n    // Add JS timeout\n    //\n    // Again,outside React `world` - this will also have effects on how state\n    // mutates\n    setTimeout(this._onTimeoutHandler, 10000);\n\n    // Make AJAX request\n    fetch('https://api.github.com/users')\n      .then(this._onAjaxCallback);\n  }\n\n  render() {\n    console.log('State in render: ' + JSON.stringify(this.state));\n\n    return (\n       <button\n         ref={this._saveButtonRef}\n         onClick={this._onClickHandler}>\n         'Click me'\n      </button>\n    );\n  }\n\n  _onClickHandler() {\n    console.log('State before (_onClickHandler): ' + JSON.stringify(this.state));\n    this.setState({\n      dollars: this.state.dollars + 10\n    });\n    console.log('State after (_onClickHandler): ' + JSON.stringify(this.state));\n  }\n\n  _onMouseLeaveHandler() {\n    console.log('State before (mouseleave): ' + JSON.stringify(this.state));\n    this.setState({\n      dollars: this.state.dollars + 20\n    });\n    console.log('State after (mouseleave): ' + JSON.stringify(this.state));\n  }\n\n  _onTimeoutHandler() {\n    console.log('State before (timeout): ' + JSON.stringify(this.state));\n    this.setState({\n      dollars: this.state.dollars + 30\n    });\n    console.log('State after (timeout): ' + JSON.stringify(this.state));\n  }\n\n  _onAjaxCallback(response) {\n    if (response.status !== 200) {\n      console.log('Error in AJAX call: ' + response.statusText);\n      return;\n    }\n    console.log('State before (AJAX call): ' + JSON.stringify(this.state));\n    this.setState({\n      dollars: this.state.dollars + 40\n    });\n    console.log('State after (AJAX call): ' + JSON.stringify(this.state));\n  }\n};\n\n// Render to DOM\nReactDOM.render(\n  <TestComponent />,\n  document.getElementById('app')\n);\n```\n\n### Possible solution?\n\nWe're used to calling setState with one parameter only, but actually, the method's signature support two.\nThe second argument that you can pass in is a callback function that will always be executed after the state has been updated (whether it's inside React's known context or outside of it).\n\n#### An example might be:\n\n```javascript\n_onClickHandler: function _onClickHandler() {\n   console.log('State before (_onClickHandler): ' + JSON.stringify(this.state));\n   this.setState({\n   dollars: this.state.dollars + 10\n   }, () => {\n   console.log('Here state will always be updated to latest version!');\n   console.log('State after (_onClickHandler): ' + JSON.stringify(this.state));\n   });\n}\n```\n\n#### A note on the async nature of setstate\n\nTo be politically correct, setState, as a method, is always synchronous.\nIt's just a function that calls something behind the scenes - enqueueState or enqueueCallback on updater.\n\nIn fact, here's setState taken directly from React source code:\n\n```javascript\nReactComponent.prototype.setState = function(partialState, callback) {\n  invariant(\n    typeof partialState === 'object' ||\n    typeof partialState === 'function' ||\n    partialState == null,\n    'setState(...): takes an object of state variables to update or a ' +\n    'function which returns an object of state variables.'\n  );\n  this.updater.enqueueSetState(this, partialState);\n  if (callback) {\n    this.updater.enqueueCallback(this, callback, 'setState');\n  }\n};\n```\n\nWhat's actually sync or async are the effects of calling setState in a React application - the reconciliation algorithm, doing the VDOM comparisons and calling render to update the real DOM.\n\n## Related links:\n- https://medium.com/@wereHamster/beware-react-setstate-is-asynchronous-ce87ef1a9cf3#.jhdhncws3\n- https://www.bennadel.com/blog/2893-setstate-state-mutation-operation-may-be-synchronous-in-reactjs.htm\n"
  },
  {
    "path": "patterns/3.dependency-injection.md",
    "content": "# Dependency Injection\n\nIn React the need of [dependency injection](https://www.youtube.com/watch?v=IKD2-MAkXyQ) is easily visible. Let's consider the following application tree:\n\n```javascript\n// Title.jsx\nexport default function Title(props) {\n  return <h1>{ props.title }</h1>;\n}\n```\n\n```javascript\n// Header.jsx\nimport Title from './Title.jsx';\nexport default function Header() {\n  return (\n    <header>\n      <Title />\n    </header>\n  );\n}\n```\n```javascript\n// App.jsx\nimport Header from './Header.jsx';\nclass App extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { title: 'React Dependency Injection' };\n  }\n  render() {\n    return <Header />;\n  }\n}\n```\nThe string \"React Dependency Injection\" should somehow reach the Title component.\nThe direct way of doing this is to pass it from App to Header and then Header to pass it to Title.\nHowever, this may work for these three components but what happens if there are multiple properties and deeper nesting.\nLots of components will have to mention properties that they are not interested in.\nIt is clear that most React components receive their dependencies via props but the question is how these dependencies reach that point.\n\n\nOne way to achieve dependency injection is by using higher-order component to inject data.\n\n```javascript\n// inject.jsx\nvar title = 'React Dependency Injection';\nexport default function inject(Component) {\n  return class Injector extends React.Component {\n    render() {\n      return (\n        <Component\n          {...this.state}\n          {...this.props}\n          title={ title }\n        />\n      )\n    }\n  };\n}\n```\n```javascript\n// Title.jsx\nexport default function Title(props) {\n  return <h1>{ props.title }</h1>;\n}\n```\n```javascript\n// Header.jsx\nimport inject from './inject.jsx';\nimport Title from './Title.jsx';\n\nvar EnhancedTitle = inject(Title);\nexport default function Header() {\n  return (\n    <header>\n      <EnhancedTitle />\n    </header>\n  );\n}\n```\nThe title is hidden in a middle layer (higher-order component) where we pass it as a prop to the original Title component.\nThat's all nice but it solves only half of the problem.\nNow we don't have to pass the title down the tree but how this data will reach the enhance.jsx helper.\n\n## Using React's context\n\nReact has the concept of context. The context is something that every component may have access to.\nIt's something like an event bus but for data. A single model which we can access from everywhere.\n\na place where we'll define the context\n```javascript\nvar context = { title: 'React in patterns' };\nclass App extends React.Component {\n  getChildContext() {\n    return context;\n  }\n  // ...\n}\n\nApp.childContextTypes = {\n  title: PropTypes.string\n};\n```\nA place where we need data\n```javascript\nclass Inject extends React.Component {\n  render() {\n    var title = this.context.title;\n  // ...\n  }\n}\nInject.contextTypes = {\n  title: PropTypes.string\n};\n```\n\n### Related links:\n- [What is Dependency Injection?](https://www.youtube.com/watch?v=IKD2-MAkXyQ)\n- [The Basics of Dependency Injection](https://www.youtube.com/watch?v=jXhdOTw1q5Q)\n- [Dependency injection in JavaScript](http://krasimirtsonev.com/blog/article/Dependency-injection-in-JavaScript)\n- [DI In React](https://github.com/krasimir/react-in-patterns/blob/master/book/chapter-10/README.md)\n"
  },
  {
    "path": "patterns/4.context-wrapper.md",
    "content": "# Context Wrapper\nIt is a good practice that our context is not just a plain object but it has an interface that allows us to store and retrieve data. For example:\n\n```javascript\n// dependencies.js\nexport default {\n  data: {},\n  get(key) {\n    return this.data[key];\n  },\n  register(key, value) {\n    this.data[key] = value;\n  }\n}\n```\nThen, if we go back to our example, the very top App component may look like that:\n```javascript\nimport dependencies from './dependencies';\ndependencies.register('title', 'React in patterns');\n\nclass App extends React.Component {\n  getChildContext() {\n    return dependencies;\n  }\n  render() {\n    return <Header />;\n  }\n}\n\nApp.childContextTypes = {\n  data: PropTypes.object,\n  get: PropTypes.func,\n  register: PropTypes.func\n};\n```\nAnd our Title component gets it's data through the context:\n```javascript\n// Title.jsx\nexport default class Title extends React.Component {\n  render() {\n    return <h1>{ this.context.get('title') }</h1>\n  }\n}\nTitle.contextTypes = {\n  data: PropTypes.object,\n  get: PropTypes.func,\n  register: PropTypes.func\n};\n```\nIdeally we don't want to specify the contextTypes every time when we need an access to the context.\nThis detail may be wrapped in a higher-order component.\nAnd even more, we may write an utility function that is more descriptive and helps us declare the exact wiring.\nie. instead of accessing the context directly with this.context.get('title') we ask the higher-order component to\nget what we need and to pass it as a prop to our component.\nFor example:\n```javascript\n// Title.jsx\nimport wire from './wire';\n\nfunction Title(props) {\n  return <h1>{ props.title }</h1>;\n}\n\nexport default wire(Title, ['title'], function resolve(title) {\n  return { title };\n});\n```\nThe wire function accepts first a React component, then an array with all the needed dependencies\n(which are registered already) and then a function which I like to call mapper.\nIt receives what's stored in the context as a raw data and returns an object which is the actual\nReact props for our component (Title). In this example we just pass what we get - a title string variable.\nHowever, in a real app this could be a collection of data stores, configuration or something else.\nSo, it's nice that we pass exactly what we need and don't pollute the components with data that they don't need.\n\nHere is how the wire function looks like:\n```javascript\nexport default function wire(Component, dependencies, mapper) {\n  class Inject extends React.Component {\n    render() {\n      var resolved = dependencies.map(this.context.get.bind(this.context));\n      var props = mapper(...resolved);\n\n      return React.createElement(Component, props);\n    }\n  }\n  Inject.contextTypes = {\n    data: PropTypes.object,\n    get: PropTypes.func,\n    register: PropTypes.func\n  };\n  return Inject;\n};\n```\nInject is a higher-order component that gets access to the context and retrieves all the items listed under dependencies array.\nThe mapper is a function receiving the context data and transforms it to props for our component.\n\n#### Non-context alternative\nUse a singleton to register/fetch all dependencies\n```javascript\nvar dependencies = {};\n\nexport function register(key, dependency) {\n  dependencies[key] = dependency;\n}\n\nexport function fetch(key) {\n  if (key in dependencies) return dependencies[key];\n  throw new Error(`\"${ key } is not registered as dependency.`);\n}\n\nexport function wire(Component, deps, mapper) {\n  return class Injector extends React.Component {\n    constructor(props) {\n      super(props);\n      this._resolvedDependencies = mapper(...deps.map(fetch));\n    }\n    render() {\n      return (\n        <Component\n          {...this.state}\n          {...this.props}\n          {...this._resolvedDependencies}\n        />\n      );\n    }\n  };\n}\n```\n\nWe'll store the dependencies in dependencies global variable (it's global for our module, not at an application level).\n\nWe then export two functions register and fetch that write and read entries.\n\nIt looks a little bit like implementing setter and getter against a simple JavaScript object.\n\nThen we have the wire function that accepts our React component and returns a higher-order component.\n\nIn the constructor of that component we are resolving the dependencies and later while rendering the original component we pass them as props.\n\nWe follow the same pattern where we describe what we need (deps argument) and extract the needed props with a mapper function.\n\nHaving the di.jsx helper we are again able to register our dependencies at the entry point of our application (app.jsx) and inject them wherever (Title.jsx) we need.\n\n```javascript\n// app.jsx\nimport Header from './Header.jsx';\nimport { register } from './di.jsx';\n\nregister('my-awesome-title', 'React in patterns');\n\nclass App extends React.Component {\n  render() {\n    return <Header />;\n  }\n}\n```\n```javascript\n// Header.jsx\nimport Title from './Title.jsx';\n\nexport default function Header() {\n  return (\n    <header>\n      <Title />\n    </header>\n  );\n}\n```\n```javascript\n// Title.jsx\nimport { wire } from './di.jsx';\n\nvar Title = function(props) {\n  return <h1>{ props.title }</h1>;\n};\n\nexport default wire(Title, ['my-awesome-title'], title => ({ title }));\n```\nIf we look at the `Title.jsx` file we'll see that the actual component and the wiring may live in different files.\nThat way the component and the mapper function become easily unit testable.\n"
  },
  {
    "path": "patterns/5.event-handlers.md",
    "content": "# Event Handlers\nBinding event handlers in the constructor.\n\nMost of the times we handle DOM events in the component that contains the elements dispatching the events.\nLike in the example below, we have a click handler and we want to run a function or method of the same component:\n\n```javascript\nclass Switcher extends React.Component {\n  render() {\n    return (\n      <button onClick={ this._handleButtonClick }>\n        click me\n      </button>\n    );\n  }\n  _handleButtonClick() {\n    console.log('Button is clicked');\n  }\n}\n```\nThat's all fine because `_handleButtonClick` is a function and we indeed pass a function to the onClick attribute.\n\nThe problem is that as it is the code doesn't keep the scope. So, if we have to use `this` inside `_handleButtonClick` we'll get an error.\n```javascript\nclass Switcher extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { name: 'React in patterns' };\n  }\n  render() {\n    return (\n      <button onClick={ this._handleButtonClick }>\n        click me\n      </button>\n    );\n  }\n  _handleButtonClick() {\n    console.log(`Button is clicked inside ${ this.state.name }`);\n    // leads to\n    // Uncaught TypeError: Cannot read property 'state' of null\n  }\n}\n```\n\nWhat we normally do is to use bind like so:\n```javascript\n<button onClick={ this._handleButtonClick.bind(this) }>\n  click me\n</button>\n```\nHowever, this means that the bind function is called again and again because we may render the button many times.\nA better approach would be to create the bindings in the constructor of the component:\n```javascript\nclass Switcher extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { name: 'React in patterns' };\n    this._buttonClick = this._handleButtonClick.bind(this);\n  }\n  render() {\n    return (\n      <button onClick={ this._buttonClick }>\n        click me\n      </button>\n    );\n  }\n  _handleButtonClick() {\n    console.log(`Button is clicked inside ${ this.state.name }`);\n  }\n}\n```\n\nThe other alternative is to use arrow functions for the onClick prop function assignment.\nArrow functions don't affect the context at invocation time (`this` value from the surrounding scope is used).\n\nFacebook by the way recommend the same technique while dealing with functions that need the context of the same component.\nThe binding in the constructor may be also useful if we pass callbacks down the tree.\n\nA short hand example using arrow functions and avoid having to use the constructor:\n\n```javascript\nclass Switcher extends React.Component {\n  state = { name: 'React in patterns' };\n\n  render() {\n    return (\n      <button onClick={ this._handleButtonClick }>\n        click me\n      </button>\n    );\n  }\n  _handleButtonClick = () => {\n    console.log(`Button is clicked inside ${ this.state.name }`);\n  }\n}\n```\n"
  },
  {
    "path": "patterns/6.flux-pattern.md",
    "content": "# Flux pattern for data handling\n\n**Simple dispatcher**\n```javascript\nvar Dispatcher = function () {\n  return {\n    _stores: [],\n    register: function (store) {\n      this._stores.push({store: store});\n    },\n    dispatch: function (action) {\n      if (this._stores.length > 0) {\n        this._stores.forEach(function (entry) {\n          entry.store.update(action);\n        });\n      }\n    }\n  }\n};\n```\nWe expect the store to have an update method(), so let's modify register to expect it.\n```javascript\nfunction register(store) {\n  if (!store || !store.update || typeof store.update !== 'function') {\n    throw new Error('You should provide a store that has an update method');\n  } else {\n    this._stores.push({store: store});\n  }\n}\n```\n**Full blown Dispatcher**\n```javascript\nvar Dispatcher = function () {\n  return {\n    _stores: [],\n    register: function (store) {\n      if (!store || !store.update) {\n        throw new Error('You should provide a store that has an `update` method.');\n      } else {\n        var consumers = [];\n        var change = function () {\n          consumers.forEach(function (l) {\n            l(store);\n          });\n        };\n        var subscribe = function (consumer, noInit) {\n          consumers.push(consumer);\n          !noInit ? consumer(store) : null;\n        };\n\n        this._stores.push({store: store, change: change});\n        return subscribe;\n      }\n    },\n    dispatch: function (action) {\n      if (this._stores.length > 0) {\n        this._stores.forEach(function (entry) {\n          entry.store.update(action, entry.change);\n        });\n      }\n    }\n  }\n};\n\nmodule.exports = {\n  create: function () {\n    var dispatcher = Dispatcher();\n\n    return {\n      createAction: function (type) {\n        if (!type) {\n          throw new Error('Please, provide action\\'s type.');\n        } else {\n          return function (payload) {\n            return dispatcher.dispatch({type: type, payload: payload});\n          }\n        }\n      },\n      createSubscriber: function (store) {\n        return dispatcher.register(store);\n      }\n    }\n  }\n};\n```\n\n### Related links:\n- https://github.com/krasimir/react-in-patterns/tree/master/patterns/flux\n"
  },
  {
    "path": "patterns/7.one-way-data-flow.md",
    "content": "# One way data flow\n\nOne-way direction data flow eliminates multiple states and deals with only one which is usually inside the store.\nTo achieve that our Store object needs logic that allows us to subscribe for changes:\n```javascript\nvar Store = {\n  _handlers: [],\n  _flag: '',\n  onChange: function (handler) {\n    this._handlers.push(handler);\n  },\n  set: function (value) {\n    this._flag = value;\n    this._handlers.forEach(handler => handler())\n  },\n  get: function () {\n    return this._flag;\n  }\n};\n```\nThen we will hook our main App component and we'll re-render it every time when the Store changes its value:\n```javascript\nclass App extends React.Component {\n  constructor(props) {\n    super(props);\n    Store.onChange(this.forceUpdate.bind(this));\n  }\n\n  render() {\n    return (\n      <div>\n        <Switcher\n          value={ Store.get() }\n          onChange={ Store.set.bind(Store) }/>\n      </div>\n    );\n  }\n}\n```\nNotice that we are using forceUpdate which is not really recommended.\n\nNormally a high-order component is used to enable the re-rendering. We used forceUpdate just to keep the example simple.\n\nBecause of this change the Switcher becomes really simple. We don't need the internal state:\n```javascript\nclass Switcher extends React.Component {\n  constructor(props) {\n    super(props);\n    this._onButtonClick = e => {\n      this.props.onChange(!this.props.value);\n    }\n  }\n\n  render() {\n    return (\n      <button onClick={ this._onButtonClick }>\n        { this.props.value ? 'lights on' : 'lights off' }\n      </button>\n    );\n  }\n}\n```\nThe benefit that comes with this pattern is that our components become dummy representation of the Store's data.\nIt's really easy to think about the React components as views (renderers).\nWe write our application in a declarative way and deal with the complexity in only one place.\n\n### Related links:\n- https://www.startuprocket.com/articles/evolution-toward-one-way-data-flow-a-quick-introduction-to-redux\n"
  },
  {
    "path": "patterns/8.presentational-vs-container.md",
    "content": "# Presentational and Container components\n\n#### Problem\nData and logic together.\n```javascript\nclass Clock extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {time: this.props.time};\n    this._update = this._updateTime.bind(this);\n  }\n\n  render() {\n    var time = this._formatTime(this.state.time);\n    return (\n      <h1>{ time.hours } : { time.minutes } : { time.seconds }</h1>\n    );\n  }\n\n  componentDidMount() {\n    this._interval = setInterval(this._update, 1000);\n  }\n\n  componentWillUnmount() {\n    clearInterval(this._interval);\n  }\n\n  _formatTime(time) {\n    var [ hours, minutes, seconds ] = [\n      time.getHours(),\n      time.getMinutes(),\n      time.getSeconds()\n    ].map(num => num < 10 ? '0' + num : num);\n\n    return {hours, minutes, seconds};\n  }\n\n  _updateTime() {\n    this.setState({time: new Date(this.state.time.getTime() + 1000)});\n  }\n}\n\nReactDOM.render(<Clock time={ new Date() }/>, ...);\n```\n#### Solution\n\nLet's split the component into two parts - container and presentation.\n\n#### Container Component\nContainers know about data, it's shape and where it comes from. They know details about how the things work or the so called business logic.\nThey receive information and format it so it is easy to use by the presentational component. Very often we use higher-order components to create containers.\nTheir render method contains only the presentational component.\n\n```javascript\n// Clock/index.js\nimport Clock from './Clock.jsx'; // <-- that's the presentational component\n\nexport default class ClockContainer extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {time: props.time};\n    this._update = this._updateTime.bind(this);\n  }\n\n  render() {\n    return <Clock { ...this._extract(this.state.time) }/>;\n  }\n\n  componentDidMount() {\n    this._interval = setInterval(this._update, 1000);\n  }\n\n  componentWillUnmount() {\n    clearInterval(this._interval);\n  }\n\n  _extract(time) {\n    return {\n      hours: time.getHours(),\n      minutes: time.getMinutes(),\n      seconds: time.getSeconds()\n    };\n  }\n\n  _updateTime() {\n    this.setState({time: new Date(this.state.time.getTime() + 1000)});\n  }\n};\n```\n#### Presentational component\nPresentational components are concerned with how the things look. They have the additional markup needed for making the page pretty.\nSuch components are not bound to anything and have no dependencies.\nVery often implemented as a stateless functional components they don't have internal state.\n\n```javascript\n// Clock/Clock.jsx\nexport default function Clock(props) {\n  var [ hours, minutes, seconds ] = [\n    props.hours,\n    props.minutes,\n    props.seconds\n  ].map(num => num < 10 ? '0' + num : num);\n\n  return <h1>{ hours } : { minutes } : { seconds }</h1>;\n};\n```\nThe nice things about containers is that they encapsulate logic and may inject data into different renderers.\nVery often a file that exports a container is not sending out a class directly but a function.\nFor example, instead of using\n\n```javascript\nimport Clock from './Clock.jsx';\nexport default class ClockContainer extends React.Component {\n  render() {\n    return <Clock />;\n  }\n}\n```\nWe may export a function that accepts the presentational component:\n```javascript\nexport default function (Component) {\n  return class Container extends React.Component {\n    render() {\n      return <Component />;\n    }\n  }\n}\n```\nUsing this technique our container is really flexible in rendering its result.\nIt will be really helpful if we want to switch from digital to analog clock representation.\n\n### Related links:\n - https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.mbglcakmp\n - https://github.com/krasimir/react-in-patterns/tree/master/patterns/presentational-and-container\n - https://medium.com/@learnreact/container-components-c0e67432e005\n"
  },
  {
    "path": "patterns/9.third-party-integration.md",
    "content": "# Third Party Integration\nMixing 3rd party integrations/libraries with React\n\nIn this example we'll see how to mix React and jQuery's UI plugin.\nWe pick tag-it jQuery plugin for the example. It transforms an unordered list to input field for managing tags:\n```html\n<ul>\n  <li>JavaScript</li>\n  <li>CSS</li>\n</ul>\n```\nTo make it work we have to include jQuery, jQuery UI and the tag-it plugin code. It works like that:\n\n```javascript\n$('<dom element selector>').tagit();\n```\nWe select a DOM element and call tagit().\n\nThe very first thing that we have to do is to force a single-render of the Tags component.\nThat's because when React adds the elements in the actual DOM we want to pass the control of them to jQuery.\nIf we skip this both React and jQuery will work on same DOM elements without knowing for each other. To achieve a single-render we have to use the lifecycle method `shouldComponentUpdate`\n\nLet's say that we want to programmatically add a new tag to the already running tag-it field.\nSuch action will be triggered by the React component and needs to use the jQuery API.\nWe have to find a way to communicate data to Tags component but still keep the single-render approach.\nTo illustrate the whole process we will add an input field to the App class and a button which if clicked will pass a string to Tags component.\n\n```javascript\nclass App extends React.Component {\n  constructor(props) {\n    super(props);\n\n    this._addNewTag = this._addNewTag.bind(this);\n    this.state = {\n      tags: ['JavaScript', 'CSS'],\n      newTag: null\n    };\n  }\n\n  _addNewTag() {\n    this.setState({newTag: this.refs.field.value});\n  }\n\n  render() {\n    return (\n      <div>\n        <p>Add new tag:</p>\n        <div>\n          <input type='text' ref='field'/>\n          <button onClick={ this._addNewTag }>Add</button>\n        </div>\n        <Tags tags={ this.state.tags } newTag={ this.state.newTag }/>\n      </div>\n    );\n  }\n}\n```\nWe use the internal state as a data storage for the value of the newly added field.\nEvery time when we click the button we update the state and trigger re-rendering of Tags component.\nHowever, because of shouldComponentUpdate we update nothing.\nThe only one change is that we get a value of the newTag prop which may be captured via another lifecycle method - componentWillReceiveProps\n```javascript\nclass Tags extends React.Component {\n  componentDidMount() {\n    this.list = $(this.refs.list);\n    this.list.tagit();\n  }\n\n  shouldComponentUpdate() {\n    return false;\n  }\n\n  componentWillReceiveProps(newProps) {\n    this.list.tagit('createTag', newProps.newTag);\n  }\n\n  render() {\n    return (\n      <ul ref='list'>\n        { this.props.tags.map((tag, i) => <li key={ i }>{ tag } </li>) }\n      </ul>\n    );\n  }\n}\n```\n### Related links:\n  - https://github.com/krasimir/react-in-patterns/tree/master/patterns/third-party\n"
  },
  {
    "path": "perf-tips/01.shouldComponentUpdate-check.md",
    "content": "# shouldComponentUpdate() check\n`shouldComponentUpdate` check to avoid expensive re-renders\n\nReact Components re-render every time their props or state change.\nSo imagine having to render the entire page every time there in an action. That takes a big load on the browser.\nThat’s where ShouldComponentUpdate comes in, whenever React is rendering the view it checks to see\nif shouldComponentUpdate is returning false/true. So whenever you have a component that’s static do yourself a favor and return false.\nOr if is not static check to see if the props/state has changed.\n\n#### Bad\n```javascript\nconst AutocompleteItem = (props) => {\n  const selectedClass = props.selected === true ? \"selected\" : \"\";\n  var path = parseUri(props.url).path;\n  path = path.length <= 0 ? props.url : \"...\" + path;\n\n  return (\n    <li\n      onMouseLeave={props.onMouseLeave}\n      className={selectedClass}>\n      <i className=\"ion-ios-eye\"\n         data-image={props.image}\n         data-url={props.url}\n         data-title={props.title}\n         onClick={props.handlePlanetViewClick}/>\n      <span\n        onMouseEnter={props.onMouseEnter}\n      >\n        <div className=\"dot bg-mint\"/>\n        {path}\n      </span>\n    </li>\n  );\n};\n```\n#### Good\n```javascript\nexport default class AutocompleteItem extends React.Component {\n  shouldComponentUpdate(nextProps, nextState) {\n    return nextProps.url !== this.props.url ||\n      nextProps.selected !== this.props.selected;\n  }\n\n  render() {\n    const {props} = this;\n    const selectedClass = props.selected === true ? \"selected\" : \"\";\n    var path = parseUri(props.url).path;\n    path = path.length <= 0 ? props.url : \"...\" + path;\n\n    return (\n      <li\n        onMouseLeave={props.onMouseLeave}\n        className={selectedClass}>\n        <i className=\"ion-ios-eye\"\n           data-image={props.image}\n           data-url={props.url}\n           data-title={props.title}\n           onClick={props.handlePlanetViewClick}/>\n        <span\n          onMouseEnter={props.onMouseEnter}>\n          <div className=\"dot bg-mint\"/>\n          {path}\n        </span>\n      </li>\n    );\n  }\n}\n```\n\n### Related links:\n- [React Performance optimization](https://medium.com/@nesbtesh/react-performance-optimization-28ec5b61fff3)\n- [React rendering misconception](https://robots.thoughtbot.com/react-rendering-misconception)\n"
  },
  {
    "path": "perf-tips/02.pure-component.md",
    "content": "# Using Pure Components\nPure Components do shallow equality checks in `shouldComponentUpdate` by default. This is intended to prevent renders when neither props nor state have changed.\n\nRecompose offers a Higher Order Component called `pure` for this purpose and React added `React.PureComponent` in v15.3.0.\n\n#### Bad\n```javascript\nexport default (props, context) => {\n  // ... do expensive compute on props ...\n  return <SomeComponent {...props} />\n}\n```\n\n#### Good\n```javascript\nimport { pure } from 'recompose';\n// This won't be called when the props DONT change\nexport default pure((props, context) => {\n  // ... do expensive compute on props ...\n  return <SomeComponent someProp={props.someProp}/>\n})\n```\n\n#### Better\n```javascript\n// This is better mainly because it uses no external dependencies.\nimport { PureComponent } from 'react';\n\nexport default class Example extends PureComponent {\n  // This won't re-render when the props DONT change\n  render() {\n    // ... do expensive compute on props ...\n    return <SomeComponent someProp={props.someProp}/>\n  }\n}\n})\n```\n\n### Related links:\n- [Recompose](https://github.com/acdlite/recompose#composition)\n- [Higher Order Components with Functional Patterns Using Recompose](https://egghead.io/courses/higher-order-components-with-functional-patterns-using-recompose)\n- [React: PureComponent](https://reactjs.org/docs/react-api.html#reactpurecomponent)\n- [Pure Components](https://www.fullstackreact.com/30-days-of-react/day-11/)\n- [Top 5 Recompose HOCs](https://medium.com/@abhiaiyer/top-5-recompose-hocs-1a4c9cc4566)\n"
  },
  {
    "path": "perf-tips/03.reselect.md",
    "content": "# Using reselect\nUse Reselect in Redux connect(mapState) -- to avoid frequent re-render.\n\n#### Bad\n```javascript\nlet App = ({otherData, resolution}) => (\n  <div>\n    <DataContainer data={otherData}/>\n    <ResolutionContainer resolution={resolution}/>\n  </div>\n);\n\nconst doubleRes = (size) => ({\n  width: size.width * 2,\n  height: size.height * 2\n});\n\nApp = connect(state => {\n  return {\n    otherData: state.otherData,\n    resolution: doubleRes(state.resolution)\n  }\n})(App);\n```\nIn this above case every time otherData in the state changes both DataContainer and ResolutionContainer\nwill be rendered even when the resolution in the state does not change.\nThis is because the doubleRes function will always return a new resolution object with a new identity.\nIf doubleRes is written with Reselect the issue goes away:\nReselect memoizes the last result of the function and returns it when called until new arguments are passed to it.\n\n#### Good\n```javascript\nimport { createSelector } from 'reselect';\nconst doubleRes = createSelector(\n  r => r.width,\n  r => r.height,\n  (width, height) => ({\n    width: width * 2,\n    height: height * 2\n  })\n);\n```\n### Related links:\n- [React](https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f#.cz2ypc2ob)\n- [Computing Derived Data: Docs](http://redux.js.org/docs/recipes/ComputingDerivedData.html)\n"
  },
  {
    "path": "perf-tips/README.md",
    "content": "# Perf Tips\n\n**Key Ideas**\n\n- Avoid Reconciliation with shouldComponentUpdate() check\n\n- Use Immutable Data Structures\n\n- Use Production Build\n\n- Profile Components with Chrome Timeline\n\n- Defer computationally expensive tasks in componentWillMount/componentDidMount by using setTimeout and/or requestAnimationFrame\n\n## Articles\n\n[Optimizing Performance: Docs](https://reactjs.org/docs/optimizing-performance.html)\n\n[Performance Engineering with React](http://benchling.engineering/performance-engineering-with-react/)\n\n[Tips to optimise rendering of a set of elements in React](https://blog.lavrton.com/how-to-optimise-rendering-of-a-set-of-elements-in-react-ad01f5b161ae)\n\n[React.js Best Practices for 2016](https://blog.risingstack.com/react-js-best-practices-for-2016/)\n"
  },
  {
    "path": "styling/01.stateless-ui-components.md",
    "content": "# Styling in stateless UI components\nKeep styles separated from the parts of the app that are tied to state.\nThat means routes, views, containers, forms, layouts, etc. should not have any styling or classes in them.\nInstead, these heavy-lifting components should be composed of primarily stateless functional UI components.\n\nForm component (with no styles/classNames) - just pure composed components\n```javascript\nclass SampleComponent extends Component {\n  render() {\n    return (\n      <form onSubmit={this.handleSubmit}>\n        <Heading children='Sign In'/>\n        <Input\n          name='username'\n          value={username}\n          onChange={this.handleChange}/>\n        <Input\n          type='password'\n          name='password'\n          value={password}\n          onChange={this.handleChange}/>\n        <Button\n          type='submit'\n          children='Sign In'/>\n      </form>\n    )\n  }\n}\n\n// Presentational component (with Styles)\nconst Button = ({\n  ...props\n  }) => {\n  const sx = {\n    fontFamily: 'inherit',\n    fontSize: 'inherit',\n    fontWeight: 'bold',\n    textDecoration: 'none',\n    display: 'inline-block',\n    margin: 0,\n    paddingTop: 8,\n    paddingBottom: 8,\n    paddingLeft: 16,\n    paddingRight: 16,\n    border: 0,\n    color: 'white',\n    backgroundColor: 'blue',\n    WebkitAppearance: 'none',\n    MozAppearance: 'none'\n  }\n\n  return (\n    <button {...props} style={sx}/>\n  )\n}\n```\n"
  },
  {
    "path": "styling/02.styles-module.md",
    "content": "# Styles module\nGenerally, hard coding styles values in a component should be avoided.\nAny values that are likely to be used across different UI components should be split into their own module.\n\n```javascript\n// Styles module\nexport const white = '#fff';\nexport const black = '#111';\nexport const blue = '#07c';\n\nexport const colors = {\n  white,\n  black,\n  blue\n};\n\nexport const space = [\n  0,\n  8,\n  16,\n  32,\n  64\n];\n\nconst styles = {\n  bold: 600,\n  space,\n  colors\n};\n\nexport default styles\n```\n\n#### Usage\n```javascript\n// button.jsx\nimport React from 'react'\nimport { bold, space, colors } from './styles'\n\nconst Button = ({\n  ...props\n  }) => {\n  const sx = {\n    fontFamily: 'inherit',\n    fontSize: 'inherit',\n    fontWeight: bold,\n    textDecoration: 'none',\n    display: 'inline-block',\n    margin: 0,\n    paddingTop: space[1],\n    paddingBottom: space[1],\n    paddingLeft: space[2],\n    paddingRight: space[2],\n    border: 0,\n    color: colors.white,\n    backgroundColor: colors.blue,\n    WebkitAppearance: 'none',\n    MozAppearance: 'none'\n  };\n\n  return (\n    <button {...props} style={sx}/>\n  )\n};\n```\n"
  },
  {
    "path": "styling/03.style-functions.md",
    "content": "# Style Functions\nSince we’re using JavaScript, we can also employ helper functions for styling elements.\n\n#### Example 1\n\nA function to create rgba values of black\n```javascript\nconst darken = (n) => `rgba(0, 0, 0, ${n})`;\ndarken(1 / 8); // 'rgba(0, 0, 0, 0.125)'\n\nconst shade = [\n  darken(0),\n  darken(1 / 8),\n  darken(1 / 4),\n  darken(3 / 8),\n  darken(1 / 2),\n  darken(5 / 8),\n  darken(3 / 4),\n  darken(7 / 8),\n  darken(1)\n];\n// So now,\n// shade[4] is 'rgba(0, 0, 0, 0.5)'\n```\n\n#### Example 2\n\nCreating a scale for margin and padding to help keep visual rhythm consistent\n```javascript\n// Modular powers of two scale\nconst scale = [\n  0,\n  8,\n  16,\n  32,\n  64\n];\n\n// Functions to get partial style objects\nconst createScaledPropertyGetter = (scale) => (prop) => (x) => {\n  return (typeof x === 'number' && typeof scale[x] === 'number')\n    ? {[prop]: scale[x]}\n    : null\n};\nconst getScaledProperty = createScaledPropertyGetter(scale);\n\nexport const getMargin = getScaledProperty('margin');\nexport const getPadding = getScaledProperty('padding');\n// Style function usage\nconst Box = ({\n  m,\n  p,\n  ...props\n  }) => {\n  const sx = {\n    ...getMargin(m),\n    ...getPadding(p)\n  };\n\n  return <div {...props} style={sx}/>\n};\n\n// Component usage\nconst Box = () => (\n  <div>\n    <Box m={2} p={3}>\n      A box with 16px margin and 32px padding\n    </Box>\n  </div>\n);\n```\n"
  },
  {
    "path": "styling/04.using-npm-modules.md",
    "content": "# Using npm modules\nFor more complex color/style transformation logic, it's always good to use it from a separate npm module (or) create one.\n\n#### Example\n\nFor darkening scales in CSS you can use `chroma-js` module\n```javascript\nimport chroma from 'chroma-js'\n\nconst alpha = (color) => (a) => chroma(color).alpha(a).css();\n\nconst darken = alpha('#000');\n\nconst shade = [\n  darken(0),\n  darken(1 / 8),\n  darken(1 / 4)\n  // More...\n];\n\nconst blueAlpha = [\n  alpha(blue)(0),\n  alpha(blue)(1 / 4),\n  alpha(blue)(1 / 2),\n  alpha(blue)(3 / 4),\n  alpha(blue)(1)\n];\n```\n"
  },
  {
    "path": "styling/05.base-component.md",
    "content": "# Base Component\n### Using a Base Component\nThere is tremendous amount of flexibility when it comes to composition in React – since components are essentially just functions.\nBy changing style details in a component to props we can make it more reusable.\n\nThe color and backgroundColor properties have been moved up to the component’s props.\nAdditionally, we’ve added a big prop to adjust the padding top and bottom.\n```javascript\nconst Button = ({\n  big,\n  color = colors.white,\n  backgroundColor = colors.blue,\n  ...props\n  }) => {\n  const sx = {\n    fontFamily: 'inherit',\n    fontSize: 'inherit',\n    fontWeight: bold,\n    textDecoration: 'none',\n    display: 'inline-block',\n    margin: 0,\n    paddingTop: big ? space[2] : space[1],\n    paddingBottom: big ? space[2] : space[1],\n    paddingLeft: space[2],\n    paddingRight: space[2],\n    border: 0,\n    color,\n    backgroundColor,\n    WebkitAppearance: 'none',\n    MozAppearance: 'none'\n  };\n\n  return (\n    <button {...props} style={sx}/>\n  )\n};\n```\n#### Usage\n```javascript\nconst Button = () => (\n  <div>\n    <Button>\n      Blue Button\n    </Button>\n    <Button big backgroundColor={colors.red}>\n      Big Red Button\n    </Button>\n  </div>\n);\n\n// By adjusting the props API of the base Button component,\n// an entire set of button styles can be created.\nconst ButtonBig = (props) => <Button {...props} big/>;\nconst ButtonGreen = (props) => <Button {...props} backgroundColor={colors.green}/>;\nconst ButtonRed = (props) => <Button {...props} backgroundColor={colors.red}/>;\nconst ButtonOutline = (props) => <Button {...props} outline/>;\n```\n"
  },
  {
    "path": "styling/06.layout-component.md",
    "content": "# Layout component\nWe can extend the idea of [Base components](./05.base-component.md) to create Layout components.\n\n#### Example\n```javascript\nconst Grid = (props) => (\n  <Box {...props}\n    display='inline-block'\n    verticalAlign='top'\n    px={2}/>\n);\n\nconst Half = (props) => (\n  <Grid {...props}\n    width={1 / 2}/>\n);\n\nconst Third = (props) => (\n  <Grid {...props}\n    width={1 / 3}/>\n);\n\nconst Quarter = (props) => (\n  <Grid {...props}\n    width={1 / 4}/>\n);\n\nconst Flex = (props) => (\n  <Box {...props}\n    display='flex'/>\n);\n\nconst FlexAuto = (props) => (\n  <Box {...props}\n    flex='1 1 auto'/>\n);\n```\n\n#### Usage\n```javascript\nconst Layout = () => (\n  <div>\n    <div>\n      <Half>Half width column</Half>\n      <Half>Half width column</Half>\n    </div>\n    <div>\n      <Third>Third width column</Third>\n      <Third>Third width column</Third>\n      <Third>Third width column</Third>\n    </div>\n    <div>\n      <Quarter>Quarter width column</Quarter>\n      <Quarter>Quarter width column</Quarter>\n      <Quarter>Quarter width column</Quarter>\n      <Quarter>Quarter width column</Quarter>\n    </div>\n  </div>\n);\n```\n\n### Related links:\n- [Github: React Layout components](https://github.com/rofrischmann/react-layout-components)\n- [Leveling Up With React: Container Components](https://css-tricks.com/learning-react-container-components/)\n- [Container Components and Stateless Functional Components in React](Leveling Up With React: Container Components)"
  },
  {
    "path": "styling/07.typography-component.md",
    "content": "# Typography Component\nWe can extend the idea of [Base components](./05.base-component.md) to create Typography components\nthis pattern helps ensure consistency and keep your styling DRY.\n\n#### Example\n```javascript\nimport React from 'react';\nimport { alternateFont, typeScale, boldFontWeight } from './styles';\n\nconst Text = ({\n  tag = 'span',\n  size = 4,\n  alt,\n  center,\n  bold,\n  caps,\n  ...props\n  }) => {\n  const Tag = tag;\n  const sx = {\n    fontFamily: alt ? alternateFont : null,\n    fontSize: typeScale[size],\n    fontWeight: bold ? boldFontWeight : null,\n    textAlign: center ? 'center' : null,\n    textTransform: caps ? 'uppercase' : null\n  };\n\n  return <Tag {...props} style={sx}/>\n};\n\nconst LeadText = (props) => <Text {...props} tag='p' size={3}/>;\nconst Caps = (props) => <Text {...props} caps/>;\nconst MetaText = (props) => <Text {...props} size={5} caps/>;\nconst AltParagraph = (props) => <Text {...props} tag='p' alt/>;\n\nconst CapsButton = ({ children, ...props }) => (\n  <Button {...props}>\n    <Caps>\n      {children}\n    </Caps>\n  </Button>\n);\n```\n#### Usage\n```javascript\nconst TypographyComponent = () => (\n  <div>\n    <LeadText>\n      This is a lead with some<Caps>all caps</Caps>.\n    It has a larger font size than the default paragraph.\n    </LeadText>\n    <MetaText>\n      This is smaller text, like form helper copy.\n    </MetaText>\n  </div>\n);\n```\n"
  },
  {
    "path": "styling/08.HOC-for-styling.md",
    "content": "# Using HOC for styling\nSometimes there are isolated UI components that only require a minimal amount of state for interaction, and using them as standalone components is sufficient\n\neg. Interactions in a Carousel\n\n#### Example: Carousel\n\nThe HOC will have a current slide index and have previous and next methods.\n```javascript\n// Higher order component\nimport React from 'react'\n// This could be named something more generic like Counter or Cycle\nconst CarouselContainer = (Comp) => {\n  class Carousel extends React.Component {\n    constructor() {\n      super();\n      this.state = {\n        index: 0\n      };\n      this.previous = () => {\n        const { index } = this.state;\n        if (index > 0) {\n          this.setState({index: index - 1})\n        }\n      };\n\n      this.next = () => {\n        const { index } = this.state;\n        this.setState({index: index + 1})\n      }\n    }\n\n    render() {\n      return (\n        <Comp\n          {...this.props}\n          {...this.state}\n          previous={this.previous}\n          next={this.next}/>\n      )\n    }\n  }\n  return Carousel\n};\nexport default CarouselContainer;\n```\n#### Using the HOC\n```javascript\n// UI component\nconst Carousel = ({ index, ...props }) => {\n  const length = props.length || props.children.length || 0;\n\n  const sx = {\n    root: {\n      overflow: 'hidden'\n    },\n    inner: {\n      whiteSpace: 'nowrap',\n      height: '100%',\n      transition: 'transform .2s ease-out',\n      transform: `translateX(${index % length * -100}%)`\n    },\n    child: {\n      display: 'inline-block',\n      verticalAlign: 'middle',\n      whiteSpace: 'normal',\n      outline: '1px solid red',\n      width: '100%',\n      height: '100%'\n    }\n  };\n\n  const children = React.Children.map(props.children, (child, i) => {\n    return (\n      <div style={sx.child}>\n        {child}\n      </div>\n    )\n  });\n\n  return (\n    <div style={sx.root}>\n      <div style={sx.inner}>\n        {children}\n      </div>\n    </div>\n  )\n};\n\n// Final Carousel component\nconst HeroCarousel = (props) => {\n  return (\n    <div>\n      <Carousel index={props.index}>\n        <div>Slide one</div>\n        <div>Slide two</div>\n        <div>Slide three</div>\n      </Carousel>\n      <Button\n        onClick={props.previous}\n        children='Previous'/>\n      <Button\n        onClick={props.next}\n        children='Next'/>\n    </div>\n  )\n};\n\n// Wrap the component with the functionality from the higher order component\nexport default CarouselContainer(HeroCarousel)\n```\nBy keeping the styling separate from the interactive state, any number of carousel variations can be created from these reusable parts.\n\n#### Usage\n```javascript\nconst Carousel = () => (\n  <div>\n    <HeroCarousel />\n  </div>\n);\n```\n"
  },
  {
    "path": "styling/README.md",
    "content": "# Styling in React\n\nHere we look into some ideas around using CSS in JS.\n\nIf you are pondering over why to use CSS in JS, I highly recommend this [talk](http://blog.vjeux.com/2014/javascript/react-css-in-js-nationjs.html) by [Vjeux](https://twitter.com/Vjeux)\n\n## Articles\n\n[Patterns for style composition in React](https://jxnblk.com/blog/patterns-for-style-composition-in-react/)\n\n[Inline style vs stylesheet performance](https://www.ctheu.com/2015/08/17/react-inline-styles-vs-css-stupid-benchmark/)\n"
  },
  {
    "path": "ux-variations/01.composing-variations.md",
    "content": "# Using Composition to handle UX variations\nCombining smaller reusable components to build a bigger UI blocks.\n\n**How do we make sure components are reusable?**\n  - By ensuring our UI components are pure presentational components (dumb)\n\n**What does reusable mean?**\n  - No data fetching within the component (do it in Redux).\n  - If data is required from API - goes into Redux\n       Via redux-thunk API calls are isolated away from the redux containers that deal with the data obtained and pass it on to the dumb component.\n\nIf we have a bunch of renderBla() functions within the component which are used in the main component render()\n  - It’s better to move it to separate components. That way it is reusable.\n\n### Example\nLogin page variations\n\nUX variations toggle features + add in additional links/markup.\n\n\nIf the UX variations are involved toggling features within a component + adding minor markup around it\n\n```javascript\nimport React, { Component } from \"react\";\nimport PropTypes from 'prop-types';\nimport SignIn from \"./sign-in\";\n\nclass MemberSignIn extends Component {\n  _renderMemberJoinLinks() {\n    return (\n      <div className=\"member-signup-links\">\n        ...\n      </div>\n    );\n  }\n\n  _routeTo() {\n    // Routing logic here\n  }\n\n  render() {\n    const {forgotEmailRoute,forgotPwdRoute, showMemberSignupLinks} = this.props;\n    return (\n      <div>\n        <SignIn\n          onForgotPasswordRequested={this._routeTo(forgotPwdRoute)}\n          onForgotEmailRequested={this._routeTo(forgotEmailRoute)}>\n          {this.props.children}\n          {showMemberSignupLinks && this._renderMemberJoinLinks()}\n        </SignIn>\n      </div>\n    );\n  }\n}\n\nexport default MemberSignIn;\n```\n\n### Related links:\n- [Slides from my talk: Building Multi-tenant UI with React](https://speakerdeck.com/vasa/building-multitenant-ui-with-react-dot-js)"
  },
  {
    "path": "ux-variations/02.toggle-ui-elements.md",
    "content": "# Toggle UI Elements\nHandling minor UX variations in the component by toggling ON/OFF features.\n\nModify the component to take in a prop to control it’s behavior.\n\n### Gotcha:\nEasy to overuse this idea by adding props for  every variation.\n  - Only add in props for features specific to the current feature that the component.\n  - Basically, not violate the Single Responsibility Principle.\n\n#### Example\nShow/Hide password feature in Login form\n\n```javascript\nclass PasswordField extends Component {\n  render() {\n    const {\n      password,\n      showHidePassword,\n      showErrorOnTop,\n      showLabels,\n      shouldComplyAda\n    } = this.props;\n    return (\n      <div>\n        <Password\n          field={password}\n          label=\"Password\"\n          showErrorOnTop={showErrorOnTop}\n          placeholder={shouldComplyAda ? \"\" : \"Password\"}\n          showLabel={showLabels}\n          showHidePassword={showHidePassword}\n        />\n      </div>\n    );\n  }\n}\n```\n\n### Related links:\n- [Slides from my talk: Building Multi-tenant UI with React](https://speakerdeck.com/vasa/building-multitenant-ui-with-react-dot-js)\n"
  },
  {
    "path": "ux-variations/03.HOC-feature-toggles.md",
    "content": "# HOC for Feature Toggles\nUsing Higher order components (HOC) for UX variations\n\neg. Toggling features On/Off\n\n```javascript\n// featureToggle.js\nconst isFeatureOn = function (featureName) {\n  // return true or false\n};\n\nimport { isFeatureOn } from './featureToggle';\n\nconst toggleOn = (featureName, ComposedComponent) => class HOC extends Component {\n  render() {\n    return isFeatureOn(featureName) ? <ComposedComponent {...this.props} /> : null;\n  }\n};\n\n// Usage\nimport AdsComponent from './Ads'\nconst Ads = toggleOn('ads', AdsComponent);\n```\n"
  },
  {
    "path": "ux-variations/04.HOC-props-proxy.md",
    "content": "# Higher Order Component - Props proxy\nThis basically helps to add/edit props passed to the Component.\n\n```javascript\nfunction HOC(WrappedComponent) {\n  return class Test extends Component {\n    render() {\n      const newProps = {\n        title: 'New Header',\n        footer: false,\n        showFeatureX: false,\n        showFeatureY: true\n      };\n\n      return <WrappedComponent {...this.props} {...newProps} />\n    }\n  }\n}\n```\n"
  },
  {
    "path": "ux-variations/05.wrapper-components.md",
    "content": "# Wrapper Components\nUsing Wrappers to handle UX/style variations\n\nFor Handling Wrapper ``<div>``’s and other markup around component, use composition!\n\nWhen you create a React component instance, you can include additional React components or JavaScript expressions between the opening and closing tags.\nParent can read its children by accessing the special this.props.children prop.\n\n```javascript\nconst SampleComponent = () => {\n  <Parent>\n    <Child />\n  </Parent>\n};\n\nconst Parent = () => {\n  // You can use class 'bla' or any other classes to handle any style variations for the same markup.\n  <div className=\"bla\">\n    {this.props.children}\n  </div>\n};\n```\n\nFYI - Wrapper component can also be made accept a tag name and then used to generate the HTML element.\nHowever, usually this is not recommended because you can't add attributes/props to it.\n\n```javascript\nconst SampleComponent = () => {\n  <Wrap tagName=\"div\" content=\"Hello World\" />\n};\n\nconst Wrap = ({ tagName, content }) => {\n  const Tag = `${tagName}`     // variable name must begin with capital letters\n  return <Tag>{content}</Tag>\n}\n```\n\n### Related links:\n- [Slides from my talk: Building Multi-tenant UI with React](https://speakerdeck.com/vasa/building-multitenant-ui-with-react-dot-js)\n"
  },
  {
    "path": "ux-variations/06.display-order-variations.md",
    "content": "# Display UI elements in different order\n\nUse a prop to specify order – Map through ReactElements and render it based on order prop.\n```javascript\nclass PageSections extends Component {\n  render() {\n    const pageItems = this.props.contentOrder.map(\n      (content) => {\n        const renderFunc = this.contentOrderMap[content];\n        return (typeof renderFunc === 'function') ? renderFunc() : null;\n      }\n    );\n\n    return (\n      <div className=\"page-content\">\n        {pageItems}\n      </div>\n    )\n  }\n}\n```\n### Related links:\n- [Slides from my talk: Building Multi-tenant UI with React](https://speakerdeck.com/vasa/building-multitenant-ui-with-react-dot-js)"
  },
  {
    "path": "ux-variations/README.md",
    "content": "# Handling UX variations for multiple brands and apps\n\n\n## [Slides from my talk](https://speakerdeck.com/vasa/building-multitenant-ui-with-react-dot-js)\n\n\nA few general coding principles which help write reusable React components\n\n## Single Responsibility Principle\n\n**In React**\n\nComponents/Containers code must essentially deal with only one chunk of the UI feature/functionality.\n\n* Eg. Shipping Address component\n\n* Address container (Only has address related fields), Name container (first and last name), Phone component, State, City and Zip code container\n\n**In Redux**\n\nAll API related call go into Redux thunks/other async handling sections (redux-promise, sagas etc)\n\n* The thunks are responsible only for the dispatching action on AJAX begin/fail and complete.\n\n* Any routing has to be dealt with the receiving component via a promise.\n\n## Keep it Simple Stupid (KISS)\n\n* Essentially, if the component needs no state - use stateless functions.\n\n* Perf matters: **Stateless fns > ES6 class components > React.createClass()**\n\n* Don’t pass any more props than required {...this.props} only if the list is big -- if not pass individual props.\n\n* Too much flows of control (If-else variations) inside the component is usually a red-flag. This most likely means - need to split up the component or create a separate variation.\n\n* Don’t optimize prematurely - Making the current component reusable with current variations known.\n\n## Articles\n\n[Building React Components for Multiple Brands and Applications](https://medium.com/walmartlabs/building-react-components-for-multiple-brands-and-applications-7e9157a39db4)\n\n"
  }
]