{"_id":"r-dynamic","_rev":"4-3d4875fe62a20475a158a9b10ef83278","time":{"1.0.0":"2020-01-12T09:45:48.088Z","created":"2020-01-13T14:04:05.423Z","1.0.1":"2020-01-13T14:04:05.552Z","modified":"2022-05-14T00:06:35.885Z","1.0.2":"2020-01-14T13:32:24.166Z"},"name":"r-dynamic","dist-tags":{"latest":"1.0.2"},"versions":{"1.0.1":{"name":"r-dynamic","version":"1.0.1","description":"A dynamic component specifically designed for React apps, supported with a couple of Vue-esque features.","author":{"name":"mozwell"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/mozwell/r-dynamic.git"},"main":"lib/index.js","module":"lib/index.es.js","jsnext:main":"lib/index.es.js","engines":{"node":">=8","npm":">=5"},"scripts":{"test":"cross-env CI=1 react-scripts-ts test --env=jsdom","test:watch":"react-scripts-ts test --env=jsdom","build":"rollup -c","start":"rollup -c -w","prepare":"npm run build && rimraf lib/**/*.map","predeploy":"cd example && yarn install && yarn run build","deploy":"gh-pages -d example/build"},"peerDependencies":{"prop-types":"^15.5.4","react":"^15.0.0 || ^16.0.0","react-dom":"^15.0.0 || ^16.0.0"},"devDependencies":{"@types/jest":"^23.1.5","@types/react":"^16.3.13","@types/react-dom":"^16.0.5","babel-core":"^6.26.3","babel-runtime":"^6.26.0","cross-env":"^5.1.4","gh-pages":"^1.2.0","react":"^16.4.1","react-dom":"^16.4.1","react-scripts-ts":"^2.16.0","rollup":"^1.29.0","rollup-plugin-babel":"^3.0.7","rollup-plugin-commonjs":"^9.3.4","rollup-plugin-node-resolve":"^3.4.0","rollup-plugin-peer-deps-external":"^2.2.0","rollup-plugin-terser":"^5.2.0","rollup-plugin-typescript2":"^0.17.0","typescript":"^2.8.3"},"gitHead":"3091a2aeb0bf4ab94d16494be835046a030b0cff","bugs":{"url":"https://github.com/mozwell/r-dynamic/issues"},"homepage":"https://github.com/mozwell/r-dynamic#readme","_id":"r-dynamic@1.0.1","_nodeVersion":"12.13.0","_npmVersion":"6.12.0","dist":{"integrity":"sha512-UU9EMSImyCdDyU0kPo2PiytD46uzfrLyF3lOGVbcci39/TGeuCcxXR6LUwERyieLkgNlVKBlip9AyWB8HitJfg==","shasum":"598945b6bc4572a444c415436212c4e3bc24e251","tarball":"https://registry.npmjs.org/r-dynamic/-/r-dynamic-1.0.1.tgz","fileCount":6,"unpackedSize":17942,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeHHjVCRA9TVsSAnZWagAAxZIP/jfPDJ7KkE5FEvY8pAdu\nGVpeHy+ngtp16qBmC9JxKE/pGPwgoW/FUBKAQQVCTJjdp39QXAbTr+SuTaF6\njZ1KA7YUjRQhaIcKQMxAR5ZCACmPsyJpPFurVV0q5lTBiKjKu3t91yBzO/+i\numW51l5HjGpUyT+eE2lPZb4a+3DQ0EmPvViixpAxlpNQLToKuwUowlbnhvZH\nyTRhYo/RDpnPZDVMMg6kSsZy2oeQ72qGev/b0yTlieec4tRPEK+4DNvKRHf2\n5o/DQTFb1qmlXFQTeew/3fTyn9JSK+BOJ1fLofmBoWmc+X7KKRnc3UXIS9y/\ngFnz0EfK59S4ZqeThH/Eo3C+8WpZBYGtozWn2gH+dAnWI9vhtq0mHI6hDCOf\nuBQOSxFRGghxST0tXE/iUcfAZ8JhCedhj4obCuZa3vXYTtnHBWnk3hBWrQqc\n08TOfbc2bzPX5qLFr40MSc5RP4qNcsWd5Qs3y/P51zU81a+MrEIaJaVr/F/g\nTdHSSPjUbjDUHuUi6OrCPS/6qBp8arn59nvcmBrIap7hN1GJ82CThDo2Nr/J\nIJvRn+Yf/S9cVAHPmU53/Ayg+lxZfVxY1H0DcP836YSh4Xr8tNr5PLPivLjw\nO6izfDLugIlC2uboMJvUya1CO2jecp1fozpPhClfgU38pk/l1omWlc1p7uJE\nMfIr\r\n=+Nhr\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQC5AsZIiOsRxrZtIEF4/v5VyGeejWQxFLVH9/0GVTPsagIhAM0DEQvb1aF4vie93KMuYiNuW8y1l42WhLjCr6I0xTLC"}]},"maintainers":[{"name":"mozwell","email":"mozwell.2020@gmail.com"}],"_npmUser":{"name":"mozwell","email":"mozwell.2020@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/r-dynamic_1.0.1_1578924245424_0.359803431135461"},"_hasShrinkwrap":false},"1.0.2":{"name":"r-dynamic","version":"1.0.2","description":"A dynamic component specifically designed for React apps, supported with a couple of Vue-esque features.","author":{"name":"mozwell"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/mozwell/r-dynamic.git"},"keywords":["react","dynamic","react-component","vue"],"main":"lib/index.js","module":"lib/index.es.js","jsnext:main":"lib/index.es.js","engines":{"node":">=8","npm":">=5"},"scripts":{"test":"cross-env CI=1 react-scripts-ts test --env=jsdom","test:watch":"react-scripts-ts test --env=jsdom","build":"rollup -c","start":"rollup -c -w","prepare":"npm run build && rimraf lib/**/*.map","predeploy":"cd example && yarn install && yarn run build","deploy":"gh-pages -d example/build"},"peerDependencies":{"prop-types":"^15.5.4","react":"^15.0.0 || ^16.0.0","react-dom":"^15.0.0 || ^16.0.0"},"devDependencies":{"@types/jest":"^23.1.5","@types/react":"^16.3.13","@types/react-dom":"^16.0.5","babel-core":"^6.26.3","babel-runtime":"^6.26.0","cross-env":"^5.1.4","gh-pages":"^1.2.0","react":"^16.4.1","react-dom":"^16.4.1","react-scripts-ts":"^2.16.0","rollup":"^1.29.0","rollup-plugin-babel":"^3.0.7","rollup-plugin-commonjs":"^9.3.4","rollup-plugin-node-resolve":"^3.4.0","rollup-plugin-peer-deps-external":"^2.2.0","rollup-plugin-terser":"^5.2.0","rollup-plugin-typescript2":"^0.17.0","typescript":"^2.8.3"},"gitHead":"2a9694971d5cc4bc316abfde60353dc3214b1c59","bugs":{"url":"https://github.com/mozwell/r-dynamic/issues"},"homepage":"https://github.com/mozwell/r-dynamic#readme","_id":"r-dynamic@1.0.2","_nodeVersion":"12.13.0","_npmVersion":"6.12.0","dist":{"integrity":"sha512-vgcB4ToVh5nTNm0VUo22UJkYa9/+HDbS78UQvlV/et2LUgtC8OX0ogGCr9P1YMT7Hu3cLYbFAWGBpRX4aAByeQ==","shasum":"9a5df891c15bbe4381d23cdb3d164f1af8345f42","tarball":"https://registry.npmjs.org/r-dynamic/-/r-dynamic-1.0.2.tgz","fileCount":6,"unpackedSize":19670,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeHcLoCRA9TVsSAnZWagAA0IUP/1RUC8IxxTkpHHISuTbQ\nTtal8DL6RtlvuMalEmDT9VcBiNfBzkwykmv35O8HZhUPX3t1p96g3rBuewBf\nz0pli5LOjy+RW0lWu90t85x4//d8SI20GrWqKkxsKBmEsXxlGuY+uG8Lj5Pu\nc8gKwmVtwbYGH5+5lBhNQ6Ht1GcJF0HS/r1hR5YxSUIffZ/N2qItDWaJgEsB\n66eXvBkQ8PKAC0xm9KTkC6TarBFIfd3lqolXvK9fgtCfNE6MYkIh/wFM8/Pq\nf4wlWAGRn1xgtDOHwdXKFhJgTjs8FZeWWqATfI6Xh0Fjbo4ZquLlTpMsrpJW\nwQ8HWbzfpHUbsbH4xIS8+3J2kxx6d9/IKUjGJZOtNQARPnaUjRBl2YRoQjiJ\n77HeBk4NtgzBien+LVHvbg7BRctUvSis7hOoOduIISAnZYy8QjXJheaN4TzZ\npTuMtmVn2UPNjW6eKgCtg/EF7o7bWMJQSdriU/P5nxDlabF4iD2IxML2oaAo\n/3ZYq1lpnfob09uTme8dbR2XEDaI7yBVOgye4AH07rdSpYjaTg288Yb/vTW6\no2WmUUC/ESO6dYfntUm5+o6o95BFsJmSJwIXEYgLcpk67eVy/nPilzp+dflV\nTLo+IasEDwWeaKVLVNeBKgYMU3LQww5B/VlsUpQ0kUKbTFjt8xAE7HBNX7xM\n8Z9T\r\n=STgl\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFt3sJixR9Fz0HI1dm6M0GP4po0G/5mUXDdp/OmObYhMAiEA+dQs204SnhCGWp5tWEHfgLTGoZC59RVKSQKY1GcxX4E="}]},"maintainers":[{"name":"mozwell","email":"mozwell.2020@gmail.com"}],"_npmUser":{"name":"mozwell","email":"mozwell.2020@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/r-dynamic_1.0.2_1579008744054_0.7516704696992618"},"_hasShrinkwrap":false}},"maintainers":[{"name":"mozwell","email":"mozwell.2020@gmail.com"}],"description":"A dynamic component specifically designed for React apps, supported with a couple of Vue-esque features.","homepage":"https://github.com/mozwell/r-dynamic#readme","repository":{"type":"git","url":"git+https://github.com/mozwell/r-dynamic.git"},"author":{"name":"mozwell"},"bugs":{"url":"https://github.com/mozwell/r-dynamic/issues"},"license":"MIT","readme":"# R-Dynamic\n\n> A dynamic component specifically designed for React apps, supported with a couple of Vue-esque features.\n\n[![NPM](https://img.shields.io/npm/v/r-dynamic.svg)](https://www.npmjs.com/package/r-dynamic)\n[![NPM Bundle Size](https://img.shields.io/bundlephobia/min/r-dynamic)](https://www.npmjs.com/package/r-dynamic)\n[![License](https://img.shields.io/npm/l/r-dynamic)](https://www.npmjs.com/package/r-dynamic)\n[![Node Version](https://img.shields.io/node/v/r-dynamic)](https://www.npmjs.com/package/r-dynamic)\n[![React Version](https://img.shields.io/npm/dependency-version/r-dynamic/peer/react)](https://www.npmjs.com/package/r-dynamic)\n[![Downloads](https://img.shields.io/npm/dt/r-dynamic)](https://www.npmjs.com/package/r-dynamic)\n\n\n## ✨ Features\n- 🎉 All React components could be dynamically rendered.\n  - (Class Components / Functional Components / Lazy Components / Context Components, etc.)\n- ✅ Dynamical rendering is also available for plain HTML elements.\n- 😎 Vue-like list rendering (v-for) is supported.\n- 👌 Vue-like conditional rendering (v-if) is supported.\n- 💎 Smooth development experience using Typescript (index.d.ts is provided).\n- ⚡️ Tiny size (1.85KB) and blazing fast (written in functional component).\n\n## 📖 Table of Contents\n- [🅿️ Prerequisites](#🅿️-prerequisites)\n- [⏩ Getting Started](#⏩-getting-started)\n- [⛵️ Guide](#⛵️-guide)\n    - [Dynamically render a React component](#dynamically-render-a-react-component)\n    - [Dynamically render an HTML element](#dynamically-render-an-html-element)\n    - [Dynamically render children without wrapper](#dynamically-render-children-without-wrapper)\n    - [Dynamically render nothing (NO CHILDREN, NO WRAPPER)](#dynamically-render-nothing-no-children-no-wrapper)\n    - [Work with async components](#work-with-async-components)\n    - [Work with Context](#work-with-context)\n    - [Work with other React components](#work-with-other-react-components)\n    - [Conditional Rendering](#conditional-rendering)\n    - [List Rendering](#list-rendering)\n        - [Rendering duplicates](#rendering-duplicates)\n        - [Iterative rendering](#iterative-rendering)\n        - [Conditional rendering for a specific item in iteration](#conditional-rendering-for-a-specific-item-in-iteration)\n        - [Set a unique key for each item](#set-a-unique-key-for-each-item)\n- [🅰️ APIs](#🅰️-apis)\n- [©️ License](#©️-license)\n- [🙏 Contribution](#🙏-contribution)\n\n## 🅿️ Prerequisites\n- React (^15.0.0 || ^16.0.0)\n- React DOM (^15.0.0 || ^16.0.0)\n\n## ⏩ Getting Started\n\n```bash\nnpm install --save r-dynamic\n```\n\n```jsx\nimport * as React from 'react'\nimport Dynamic from 'r-dynamic'\n```\n\n## ⛵️ Guide\n\n### Dynamically render a React component\nYou could render a **class component** dynamically:\n```js\nclass Button extends React.Component {\n  render() {\n    return <button>{this.props.text}</button>\n  }\n}\n\n<Dynamic $as={Button} text='Click Me' />\n```\nit would be rendered as if you use the following line:\n```js\n<Button text='Click Me' />\n```\n\n**Functional component** is also supported:\n```js\nfunction Button(props) {\n  return <button>{props.text}</button>;\n}\n\n<Dynamic $as={Button} text='Click Me' />\n```\n\n### Dynamically render an HTML element\nYou could render a plain HTML element dynamically by **passing a string** to $as:\n```js\n<Dynamic $as='p' style='width: 350px;'>This is a paragraph.</Dynamic>\n```\nYou will get the same result as the following:\n```js\n<p style='width: 350px;'>This is a paragraph.</p>\n```\n\n### Dynamically render children without wrapper\nIf you pass **null / undefined / ''(an empty string)** to $as, the wrapper would not be rendered while its children still get rendered:\n```js\n<Dynamic $as={null}> // it works like <React.Fragment> in this way.\n  <p>This is a child without any wrapper.</p>\n</Dynamic>\n```\nYou will get the same result as the following:\n```js\n<p>This is a child without any wrapper.</p>\n```\n\n### Dynamically render nothing (NO CHILDREN, NO WRAPPER)\nAs mentioned above, you could pass a React class component or functional component for **$as**. Furthermore, you could even pass a **function** as long as it returns a **ReactChild or null**. In this way, you can get control of the entire component (its wrapper as well as children).\n\nFor instance, we could dynamically render nothing (LITERALLY):\n```js\n<h1>LOOK AT THIS!</h1>\n<Dynamic $as={() => null}>\n  <p>This paragraph will not be shown.</p>\n</Dynamic>\n```\n\nIt works just like we don't have rendered anything yet:\n```js\n<h1>LOOK AT THIS!</h1>\n```\n\n### Work with async components\nFirst of all, I recommend you to use [react-loadable](https://github.com/jamiebuilds/react-loadable) in circumstances where you need async components, since it provides a sync-like development experience and works well in SSR (Server-Side Rendering) projects.\n\nHere is an example:\n```js\n/** button.js */\nconst Button = (props) => {\n  return <button>{props.text}</button>\n}\nexport default Button\n```\n\n```js\nimport Loadable from 'react-loadable'\n\nconst AsyncButton = Loadable({\n  loader: () => import('./button.js'),\n  loading: () => <div>loading</div>,\n});\n\nexport const Showcase = (props) => {\n  return <Dynamic $as={AsyncButton} text='Click Me' />\n}\n```\n\nOf course, you could use React.lazy instead, since it is embedded in React since v16.6. Here goes another example:\n```js\n/** button.js */\nconst Button = (props) => {\n  return <button>{props.text}</button>\n}\nexport default Button\n```\n\n```js\nconst AsyncButton = React.lazy(() => import('./button.js'))\n\nexport const Showcase = (props) => {\n  return (\n    <React.Suspense fallback={<div>Loading...</div>}>\n      <Dynamic $as={AsyncButton} text='Click Me' />\n    </React.Suspense>\n  )\n}\n```\nThis kind of practice has the following weaknesses:\n- React.lazy components should be enclosed in React.Suspense, otherwise it would raise an error.\n- It cannot work in SSR projects.\n\n### Work with Context\nDynamical rendering of Context is supported:\n```js\nconst ThemeContext = React.createContext('light');\nconst {Consumer, Provider} = ThemeContext\n\nclass Title extends React.Component {\n  static contextType = ThemeContext;\n  render() {\n    return <h3>{this.context}</h3>\n  }\n}\n\nexport const CustomizedTitle = (props) => {\n  return (\n    <DynamicComponent $as={Provider} value='dark'>\n      <Title />\n    </DynamicComponent>\n  )\n}\n```\nCustomizedTitle will be rendered as follows:\n```js\n<h3>dark</h3>\n```\n\n### Work with other React components\nR-Dynamic uses the definition of ExoticComponent interface as a tool to differentiate between normal React components (class components and functional components) and those special ones (they are also callable but with an additional $$typeof attribute). In this way, forwardRef, Fragment, memo and other components alike could be dynamically rendered since they all confirm to the definition. Enjoy it!\n\n### Conditional Rendering\nSimilar to the v-if directive in Vue, we can use **$if** to toggle between rendering & not rendering:\n```js\n<Dynamic $as='div' $if={false}>\n  <span>show me or not</span>\n</Dynamic>\n```\nIf you pass **false** to **$if**, R-Dynamic will render **null** so the entire component DOM tree will disappear. Otherwise, it will render as normal.\n\n\n### List Rendering\n#### Rendering duplicates\nSimilar to the v-for directive in Vue, we can use **$for** to render items for a specific number of times:\n```js\n<ul>\n  <Dynamic $as='li' $for={5}>\n    <span>this is a list item</span>\n  </Dynamic>\n</ul>\n```\nInstead of repetitive coding:\n```js\n<ul>\n  <li>\n    <span>this is a list item</span>\n  </li>\n  <li>\n    <span>this is a list item</span>\n  </li>\n  <li>\n    <span>this is a list item</span>\n  </li>\n  <li>\n    <span>this is a list item</span>\n  </li>\n  <li>\n    <span>this is a list item</span>\n  </li>\n</ul>\n```\n\n#### Iterative rendering\nWe can also use **$for** to iterate items in a data source (array / object).\n```js\nconst arr = ['red', 'blue', 'orange', 'yellow']\n\n<ul>\n  <Dynamic\n    $as='li'\n    $for={arr}\n    $for_render={(item, index) => <span>{index} -- This is {item}</span>}\n  />\n</ul>\n```\nIt will be rendered as follows:\n```js\n<ul>\n  <li>\n    <span>0 -- this is red</span>\n  </li>\n  <li>\n    <span>1 -- this is blue</span>\n  </li>\n  <li>\n    <span>2 -- this is orange</span>\n  </li>\n  <li>\n    <span>3 -- this is yellow</span>\n  </li>\n</ul>\n```\nHere we notice a special prop: **$for_render**. We don't pass children between the tags since there is no way for us to access the data source provided by **$for**. By using **$for_render**, we could receive item in the data source and render in accordance with it.\n\nIf you pass an **object** instead of array, then the first parameter of **$for_render** function will be **value**, not item; while the second parameter will be **key**, not index.\n\n#### Conditional rendering for a specific item in iteration\nWe could use **$for_if** to control whether a specific item in the iteration should be rendered:\n```js\nconst arr = ['red', 'blue', 'orange', 'yellow']\n\n<ul>\n  <Dynamic\n    $as='li'\n    $for={arr}\n    $for_if={(item, index) => item % 2 !== 0}\n    $for_render={(item, index) => <span>{index} -- This is {item}</span>}\n  />\n</ul>\n```\nWe will get the following result:\n```js\n<ul>\n  <li>\n    <span>1 -- this is blue</span>\n  </li>\n  <li>\n    <span>3 -- this is yellow</span>\n  </li>\n</ul>\n```\n\n#### Set a unique key for each item\nBy default, each item in the iteration is assigned with its corresponding index. Though unique to some extent, it is mutable, which could lead to low performance under some circumstances. Thus, I recommend you to assign a unique and immutable key to each item via **$for_key** prop:\n```js\nconst obj = [\n  {name: 'Bob', gender: 'male', id: 'MNREX0J87K'},\n  {name: 'Alice', gender: 'female', id: '5LB7G5YN0B'},\n  {name: 'Costa', gender: 'male', id: 'YLBI1KE6VR'}\n]\n\n<ul>\n  <Dynamic\n    $as='li'\n    $for={obj}\n    $for_key={(item) => item.id}\n    $for_render={(item, index) => <span>{item.name} -- {item.gender}</span>}\n  />\n</ul>\n```\n\n## 🅰️ APIs\n| *Property*     |  *Type*    | *Required*     |  *Default Value*    |  *Description*    |\n| :------------- | :------------- | :------------- | :------------- | :------------- |\n| $as        | string \\| FunctionComponent \\| ComponentClass \\| ExoticComponent \\| null \\| undefined       | ❌       | undefined       | The wrapper element needs to be rendered, which could be a plain HTML element, React element or just nothing (its children could be rendered alone).     |\n| $if        | boolean       | ❌       | true       | To control whether the entire DOM tree of the component should be rendered or not, similar to the v-if directive in Vue.      |\n| $for       | Array \\| object \\| number       | ❌       | N/A       | To iterate the data source and render each item respectively, similar to the v-for directive in Vue. Pass a number if you want to see the component rendered for a specific number of times. |\n| $for_if    | (value?: any, key?: number \\| string) => boolean   | ❌       | () => true    | To control whether a specific item in the iteration should be rendered, using with $for. If you want to batch all the items, use $if instead. |\n| $for_key   | (item: any) => any      | ❌       |  *(Unique index for each item)*      | To tag each item in the iteration with a unique key. Note that if you use duplicate keys, an error would be raised.     |\n| $for_render| (item?: any, index?: number \\| string) => React.ReactChild       | ❌       | N/A       |  By default, the *children* prop would be rendered as the children of the component. To override it, you could use the *$for_render* prop, which give you a full access to the data source of each item, so as to render each item with its unique data.    |\n| children   | ReactChild       | ❌      | N/A       | The children need to get rendered.       |\n\n## ©️ License\n\nMIT © [mozwell](https://github.com/mozwell)\n\n## 🙏 Contribution\nAll kinds of contribution are welcomed, please submit PRs if you've got any good idea. Issues are also kindly appreciated.\n","readmeFilename":"README.md","keywords":["react","dynamic","react-component","vue"]}