├── .eslintignore ├── .eslintrc ├── .gitignore ├── CONTRIBUTE.md ├── LICENSE ├── README.md ├── demo ├── components │ ├── CheckboxField.jsx │ ├── ContactForm.jsx │ └── StringField.jsx ├── index.html ├── index.jsx ├── package-lock.json ├── package.json └── webpack.config.js ├── dist ├── react-json-schema.js └── react-json-schema.min.js ├── lib └── ReactJsonSchema.js ├── package-lock.json ├── package.json ├── spec ├── ReactJsonSchemaSpec.js ├── index.html ├── spec.entry.js └── support │ └── jasmine.json ├── webpack.config.dist.js └── webpack.config.spec.js /.eslintignore: -------------------------------------------------------------------------------- 1 | demo 2 | spec/spec.js 3 | *.md 4 | webpack.config.spec.js 5 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "airbnb", 3 | "rules": { 4 | "comma-dangle": 0, 5 | "object-curly-newline": ["error", { "multiline": true, "minProperties": 5 }] 6 | }, 7 | "parserOptions": { 8 | "ecmaVersion": 6, 9 | "sourceType": "module", 10 | "ecmaFeatures": { 11 | "jsx": true, 12 | "experimentalObjectRestSpread": true 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea 3 | .iml 4 | .git 5 | node_modules 6 | npm-debug.log 7 | spec/spec.js 8 | demo/build 9 | -------------------------------------------------------------------------------- /CONTRIBUTE.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Code of Conduct: Don't intentionally offend others, and don't look for offense from others. 4 | 5 | [Open an issue](https://github.com/TechniqueSoftware/react-json-schema/issues/new) to start a converstation about anything related to this project. 6 | 7 | To participate by contributing, start by cloning the repo: 8 | 9 | git clone https://github.com/TechniqueSoftware/react-json-schema.git 10 | 11 | Then install the node modules: 12 | 13 | npm install 14 | 15 | Make your changes using an IDE that has a linter that recognizes ESLint enabled. 16 | 17 | Write and run tests: 18 | 19 | npm test 20 | 21 | Test your contribution using the demo as a playground (http://localhost:8080): 22 | 23 | npm run demo 24 | 25 | Consider the maintainer's commitments and expectations found below before submitting a pull request. If you submit a pull request, briefly explain your changes. If your contribution relates to an existing issue, please link the issue in the pull request. 26 | 27 | These are the maintainer's commitments to package users and contributers: 28 | * Any contribution must undergo code review before being accepted 29 | * Any contribution must have associated tests, and all tests must pass, before being accepted 30 | * Maintainers build each release; it's not necessary for you to commit a build if you do not need to use your fork immediately 31 | * Maintainers release the package using [semantic versioning](https://semver.org/) 32 | 33 | These are the maintainer's expectations: 34 | * Contributions align with the project's purpose: "This library constructs React elements from JSON by mapping JSON definitions to React components that you expose" 35 | * You have used a linter and have followed the ESLint style guide -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2015-2018 Technique Software 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-json-schema 2 | 3 | `npm install react-json-schema` 4 | 5 | Construct React elements from JSON by mapping JSON definitions to React components. Use react-json-schema for data-driven layouts, or as an abstraction layer for React components and props. 6 | 7 | Render anywhere (as long as it's DOM)! Since react-json-schema does not perform any rendering, the method in which you want to render is up to you. For example, you can use ReactDOMServer.render, ReactDOM.renderToString, etc. if you'd like. This also means JSX is not a dependency for react-json-schema. 8 | 9 | [Quick Documentation and Examples](http://techniquesoftware.github.io/react-json-schema/) 10 | 11 | ### Full Documentation 12 | 13 | * [Schema](#schema) 14 | * [Dynamic Children and Keys](#dynamic-children-and-keys) 15 | * [Component Mapping](#component-mapping) 16 | * [Complete Example](#complete-example) 17 | 18 | #### Schema 19 | 20 | The primary resource needed is a defined schema in JSON or a JavaScript object literal. It's recommended that schema attributes mainly define React component props. The parser explicitly handles the following attributes: 21 | - **component**: _MUST_ exist and be defined by a string or React component (must be a string if describing a native HTML tag) 22 | - **children**: _MAY_ exist to define sub-components 23 | - **text**: _MAY_ exist to as a string to define inner HTML text (overrides children) 24 | - **key**: _MAY_ exist to define a key for dynamic children 25 | 26 | Example JSON schema 27 | ```js 28 | const schema = { 29 | "component": "CommentList", 30 | "children": [ 31 | { 32 | "component": "Comment", 33 | "author": "Pete Hunt", 34 | "children": "This is one comment" 35 | }, 36 | { 37 | "component": "Comment", 38 | "author": "Jordan Walke", 39 | "children": "This is *another* comment" 40 | }, 41 | { 42 | "component": "a", 43 | "href": "#help", 44 | "text": "I need help" 45 | } 46 | ] 47 | }; 48 | ``` 49 | 50 | Example JS literal 51 | ```js 52 | ... 53 | { 54 | "component": Comment, 55 | "author": "Pete Hunt", 56 | "children": "This is one comment" 57 | }, 58 | ... 59 | ``` 60 | 61 | ##### Dynamic Children and Keys 62 | 63 | When arrays of components exist (like children), react-json-schema will resolve a key for the element, which follows the rules for [dynamic children](https://facebook.github.io/react/docs/multiple-components.html#dynamic-children). It will either use a custom key if defined, or resolve a numeric key based on the array index. 64 | 65 | Example of defining child keys 66 | ```js 67 | ... 68 | { 69 | "component": "Comment", 70 | "key": "0ab19f8e", // defined key 71 | "author": "Pete Hunt", 72 | "children": "This is one comment" 73 | }, 74 | ... 75 | ``` 76 | 77 | #### Component Mapping 78 | 79 | React components need to be exposed to the react-json-schema so that the parser can create React elements. If the schema contains object literals with component references, the schema is exposing the React components and no additional configuration is needed. If the schema does not contain references to components, the components can be exposed via `setComponentMap`. 80 | 81 | Example for exposing non-exposed components (ES6) 82 | ```js 83 | /* es6 object literal shorthand: { ContactForm } == { ContactForm: ContactForm } */ 84 | contactForm.setComponentMap({ ContactForm, StringField }); 85 | ``` 86 | 87 | #### Parsing 88 | 89 | Use `parseSchema` to render React elements. It returns the root node. Note that if your schema's root is an array, you'll have to wrap the schema in an element. 90 | 91 | Example (ES6) 92 | ```js 93 | ReactDOM.render(contactForm.parseSchema(schema), 94 | document.getElementById('contact-form')); 95 | ``` 96 | 97 | #### Complete Example 98 | 99 | ```js 100 | import ReactDOM from 'react-dom'; 101 | import ReactJsonSchema from 'react-json-schema'; 102 | 103 | import FormStore from 'FormStore'; 104 | import CommentList from 'CommentList'; 105 | import Comment from 'Comment'; 106 | 107 | // For this example, let's pretend I already have data and am ignorant of actions 108 | const schema = FormStore.getFormSchema(); 109 | const view = new ReactJsonSchema(); 110 | 111 | view.setComponentMap({ CommentList, Comment }); 112 | 113 | ReactDOM.render(view.parseSchema(schema), 114 | document.getElementById('content')); 115 | ``` 116 | 117 | ### Demo an Example Codebase 118 | 119 | To run the demo 120 | * `cd demo && npm install` 121 | * `npm start` 122 | * The app will be served at http://localhost:8080 123 | 124 | ### Contribution and Code of Conduct 125 | 126 | If you'd like to ask a question, raise a concern, or contribute, please follow our [contribution guidelines](CONTRIBUTE.md). 127 | 128 | ### Alternatives 129 | 130 | * [react-jsonschema-form](https://github.com/mozilla-services/react-jsonschema-form): A React component for building Web forms from JSON Schema. This library further abstracts React components, making it easier to build forms. Also, it comes with components. React-json-schema is a lighter alternative that allows the use of any components. 131 | 132 | ### Roadmap 133 | 134 | * Playground on our public site for discoverability 135 | * Possibility of react-native-json-schema 136 | -------------------------------------------------------------------------------- /demo/components/CheckboxField.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { FormGroup,Radio } from 'react-bootstrap'; 4 | 5 | class CheckboxField extends React.Component { 6 | 7 | constructor(props) { 8 | super(props); 9 | } 10 | 11 | renderCheckboxes() { 12 | const checkboxes = []; 13 | this.props.checkboxes.forEach(function loop(checkbox, index) { 14 | checkboxes.push( 15 | {checkbox.label} 16 | ); 17 | }); 18 | return checkboxes; 19 | } 20 | 21 | render() { 22 | const checkboxes = this.renderCheckboxes(); 23 | return ( 24 | 25 | {checkboxes} 26 | 27 | ); 28 | } 29 | } 30 | 31 | CheckboxField.propTypes = { 32 | checkboxes: PropTypes.arrayOf( 33 | PropTypes.shape({ 34 | label: PropTypes.string.isRequired 35 | }).isRequired 36 | ).isRequired 37 | }; 38 | 39 | export default CheckboxField; 40 | -------------------------------------------------------------------------------- /demo/components/ContactForm.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { Button, Grid, Col, Row } from 'react-bootstrap'; 4 | 5 | class ContactForm extends React.Component { 6 | 7 | constructor(props) { 8 | super(props); 9 | } 10 | 11 | alertSubmit() { 12 | alert('Hey, you submitted the form!'); 13 | } 14 | 15 | render() { 16 | return ( 17 | 18 | 19 | 20 |

{this.props.title}

21 |
22 | {this.props.children} 23 | 24 |
25 | 26 |
27 |
28 | ); 29 | } 30 | } 31 | 32 | ContactForm.propTypes = { 33 | title: PropTypes.string.isRequired, 34 | children: PropTypes.arrayOf(PropTypes.element) 35 | }; 36 | 37 | export default ContactForm; 38 | -------------------------------------------------------------------------------- /demo/components/StringField.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { FormGroup, ControlLabel, FormControl, HelpBlock } from 'react-bootstrap'; 4 | 5 | const alphaRegex = /^$|[A-Z]+$/i; 6 | 7 | class StringField extends React.Component { 8 | 9 | constructor(props) { 10 | super(props); 11 | this.state = { value: '' }; 12 | } 13 | 14 | validateInput(event) { 15 | if (alphaRegex.test(event.target.value)) { 16 | this.setState({ value: event.target.value }); 17 | } 18 | } 19 | 20 | render() { 21 | const { label, name, help, ...rest } = this.props; 22 | return ( 23 | 24 | {label} 25 | 26 | {help && {help}} 27 | 28 | ); 29 | } 30 | } 31 | 32 | StringField.propTypes = { 33 | label: PropTypes.string.isRequired, 34 | name: PropTypes.string.isRequired, 35 | help: PropTypes.string 36 | }; 37 | 38 | export default StringField; 39 | -------------------------------------------------------------------------------- /demo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Demo: react-json-schema 6 | 7 | 8 | 9 |
10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /demo/index.jsx: -------------------------------------------------------------------------------- 1 | import ReactDOM from 'react-dom'; 2 | import ContactForm from './components/ContactForm'; 3 | import StringField from './components/StringField'; 4 | import CheckboxField from './components/CheckboxField'; 5 | 6 | // If a package dependency: import ReactJsonSchema from 'react-json-schema'; 7 | import ReactJsonSchema from '../lib/ReactJsonSchema'; 8 | 9 | const welcomeSchema = { 10 | 'component': 'h2', 11 | 'className': 'text-center', 12 | 'text': 'Hello World!' 13 | }; 14 | 15 | const welcomeBanner = new ReactJsonSchema(); 16 | ReactDOM.render(welcomeBanner.parseSchema(welcomeSchema), document.getElementById('welcome-banner')); 17 | 18 | const formSchema = { 19 | 'component': 'ContactForm', 20 | 'title': 'Tell us a little about yourself, we\'d appreciate it', 21 | 'children': [ 22 | { 23 | 'component': 'StringField', 24 | 'label': 'What\'s your name', 25 | 'name': 'fullname', 26 | 'help': 'It\'s okay, don\'t be shy :)' 27 | }, 28 | { 29 | 'component': 'CheckboxField', 30 | 'checkboxes': [ 31 | { 32 | 'label': 'I\'m already checked!', 33 | 'defaultChecked': true, 34 | 'key': 0 35 | }, 36 | { 37 | 'label': 'Here\'s another', 38 | 'key': 10 39 | } 40 | ] 41 | } 42 | ] 43 | }; 44 | 45 | const componentMap = { ContactForm, StringField, CheckboxField }; 46 | const contactForm = new ReactJsonSchema(); 47 | contactForm.setComponentMap(componentMap); 48 | 49 | ReactDOM.render(contactForm.parseSchema(formSchema), document.getElementById('json-react-schema')); 50 | -------------------------------------------------------------------------------- /demo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-json-schema-demo", 3 | "version": "1.0.0", 4 | "description": "Need to test ReactJsonSchema in the wild? This is where you'd do it.", 5 | "author": { 6 | "name": "A collaborative project overseen by Club OS", 7 | "url": "https://club-os.com/" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/TechniqueSoftware/react-json-schema" 12 | }, 13 | "license": "Apache-2.0", 14 | "bugs": { 15 | "url": "https://github.com/TechniqueSoftware/react-json-schema/issues" 16 | }, 17 | "scripts": { 18 | "start": "webpack-dev-server --progress --colors --inline" 19 | }, 20 | "engines": { 21 | "node": ">=6.4.0" 22 | }, 23 | "devDependencies": { 24 | "ajv": "^6.1.1", 25 | "bootstrap": "^3.3.7", 26 | "file-loader": "^1.1.6", 27 | "path": "^0.12.7", 28 | "prop-types": "^15.6.0", 29 | "react-bootstrap": "^0.32.1", 30 | "react-dom": "^16.2.0", 31 | "webpack": "^3.11.0", 32 | "webpack-dev-server": "^2.11.1" 33 | }, 34 | "dependencies": { 35 | "react": "^16.3.2" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /demo/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = { 4 | entry: path.join(__dirname, 'index.jsx'), 5 | output: { 6 | filename: 'bundle.js', 7 | path: path.join(__dirname, 'build') 8 | }, 9 | module: { 10 | rules: [ 11 | { 12 | test: /\.(js|jsx)$/, 13 | exclude: [ 14 | path.join(__dirname, '../dist'), 15 | /node_modules/ 16 | ], 17 | use: [{ 18 | loader: 'babel-loader', 19 | options: { 20 | presets: ['react', 'env'], 21 | plugins: ['transform-es2015-destructuring', 'transform-object-rest-spread'] 22 | } 23 | }] 24 | } 25 | ] 26 | }, 27 | resolve: { 28 | modules: [ 29 | path.join(__dirname, '../lib'), 30 | path.join(__dirname, '../dist'), 31 | 'node_modules' 32 | ], 33 | extensions: ['.js', '.json', '.jsx'] 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /dist/react-json-schema.js: -------------------------------------------------------------------------------- 1 | (function webpackUniversalModuleDefinition(root, factory) { 2 | if(typeof exports === 'object' && typeof module === 'object') 3 | module.exports = factory(require("react")); 4 | else if(typeof define === 'function' && define.amd) 5 | define(["react"], factory); 6 | else if(typeof exports === 'object') 7 | exports["ReactJsonSchema"] = factory(require("react")); 8 | else 9 | root["ReactJsonSchema"] = factory(root["React"]); 10 | })(typeof self !== 'undefined' ? self : this, function(__WEBPACK_EXTERNAL_MODULE_0__) { 11 | return /******/ (function(modules) { // webpackBootstrap 12 | /******/ // The module cache 13 | /******/ var installedModules = {}; 14 | /******/ 15 | /******/ // The require function 16 | /******/ function __webpack_require__(moduleId) { 17 | /******/ 18 | /******/ // Check if module is in cache 19 | /******/ if(installedModules[moduleId]) { 20 | /******/ return installedModules[moduleId].exports; 21 | /******/ } 22 | /******/ // Create a new module (and put it into the cache) 23 | /******/ var module = installedModules[moduleId] = { 24 | /******/ i: moduleId, 25 | /******/ l: false, 26 | /******/ exports: {} 27 | /******/ }; 28 | /******/ 29 | /******/ // Execute the module function 30 | /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); 31 | /******/ 32 | /******/ // Flag the module as loaded 33 | /******/ module.l = true; 34 | /******/ 35 | /******/ // Return the exports of the module 36 | /******/ return module.exports; 37 | /******/ } 38 | /******/ 39 | /******/ 40 | /******/ // expose the modules object (__webpack_modules__) 41 | /******/ __webpack_require__.m = modules; 42 | /******/ 43 | /******/ // expose the module cache 44 | /******/ __webpack_require__.c = installedModules; 45 | /******/ 46 | /******/ // define getter function for harmony exports 47 | /******/ __webpack_require__.d = function(exports, name, getter) { 48 | /******/ if(!__webpack_require__.o(exports, name)) { 49 | /******/ Object.defineProperty(exports, name, { 50 | /******/ configurable: false, 51 | /******/ enumerable: true, 52 | /******/ get: getter 53 | /******/ }); 54 | /******/ } 55 | /******/ }; 56 | /******/ 57 | /******/ // getDefaultExport function for compatibility with non-harmony modules 58 | /******/ __webpack_require__.n = function(module) { 59 | /******/ var getter = module && module.__esModule ? 60 | /******/ function getDefault() { return module['default']; } : 61 | /******/ function getModuleExports() { return module; }; 62 | /******/ __webpack_require__.d(getter, 'a', getter); 63 | /******/ return getter; 64 | /******/ }; 65 | /******/ 66 | /******/ // Object.prototype.hasOwnProperty.call 67 | /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; 68 | /******/ 69 | /******/ // __webpack_public_path__ 70 | /******/ __webpack_require__.p = ""; 71 | /******/ 72 | /******/ // Load entry module and return exports 73 | /******/ return __webpack_require__(__webpack_require__.s = 1); 74 | /******/ }) 75 | /************************************************************************/ 76 | /******/ ([ 77 | /* 0 */ 78 | /***/ (function(module, exports) { 79 | 80 | module.exports = __WEBPACK_EXTERNAL_MODULE_0__; 81 | 82 | /***/ }), 83 | /* 1 */ 84 | /***/ (function(module, exports, __webpack_require__) { 85 | 86 | "use strict"; 87 | 88 | 89 | Object.defineProperty(exports, "__esModule", { 90 | value: true 91 | }); 92 | 93 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 94 | 95 | var _react = __webpack_require__(0); 96 | 97 | var _reactDomFactories = __webpack_require__(2); 98 | 99 | var _reactDomFactories2 = _interopRequireDefault(_reactDomFactories); 100 | 101 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 102 | 103 | function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } 104 | 105 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 106 | 107 | var componentMapCollection = new WeakMap(); 108 | 109 | var ReactJsonSchema = function () { 110 | function ReactJsonSchema() { 111 | _classCallCheck(this, ReactJsonSchema); 112 | } 113 | 114 | _createClass(ReactJsonSchema, [{ 115 | key: 'parseSchema', 116 | value: function parseSchema(schema) { 117 | var element = null; 118 | var elements = null; 119 | if (Array.isArray(schema)) { 120 | elements = this.parseSubSchemas(schema); 121 | } else if (schema) { 122 | element = this.createComponent(schema); 123 | } 124 | return element || elements; 125 | } 126 | }, { 127 | key: 'parseSubSchemas', 128 | value: function parseSubSchemas() { 129 | var _this = this; 130 | 131 | var subSchemas = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; 132 | 133 | var Components = []; 134 | var index = 0; 135 | Object.keys(subSchemas).forEach(function (key) { 136 | var subSchema = subSchemas[key]; 137 | subSchema.key = typeof subSchema.key !== 'undefined' ? subSchema.key : index; 138 | Components.push(_this.parseSchema(subSchema)); 139 | index += 1; 140 | }); 141 | return Components; 142 | } 143 | }, { 144 | key: 'createComponent', 145 | value: function createComponent(schema) { 146 | // eslint-disable-next-line no-unused-vars 147 | var component = schema.component, 148 | children = schema.children, 149 | text = schema.text, 150 | rest = _objectWithoutProperties(schema, ['component', 'children', 'text']); 151 | 152 | var Component = this.resolveComponent(schema); 153 | var Children = typeof text !== 'undefined' ? text : this.resolveComponentChildren(schema); 154 | return (0, _react.createElement)(Component, rest, Children); 155 | } 156 | }, { 157 | key: 'resolveComponent', 158 | value: function resolveComponent(schema) { 159 | var componentMap = this.getComponentMap(); 160 | var Component = null; 161 | if (Object.prototype.hasOwnProperty.call(schema, 'component')) { 162 | if (schema.component === Object(schema.component)) { 163 | Component = schema.component; 164 | } else if (componentMap && componentMap[schema.component]) { 165 | Component = componentMap[schema.component]; 166 | } else if (Object.prototype.hasOwnProperty.call(_reactDomFactories2.default, schema.component)) { 167 | Component = schema.component; 168 | } 169 | } else { 170 | throw new Error('ReactJsonSchema could not resolve a component due to a missing component \n attribute in the schema.'); 171 | } 172 | return Component; 173 | } 174 | }, { 175 | key: 'resolveComponentChildren', 176 | value: function resolveComponentChildren(schema) { 177 | return Object.prototype.hasOwnProperty.call(schema, 'children') ? this.parseSchema(schema.children) : undefined; 178 | } 179 | }, { 180 | key: 'getComponentMap', 181 | value: function getComponentMap() { 182 | return componentMapCollection.get(this); 183 | } 184 | }, { 185 | key: 'setComponentMap', 186 | value: function setComponentMap(componentMap) { 187 | componentMapCollection.set(this, componentMap); 188 | } 189 | }]); 190 | 191 | return ReactJsonSchema; 192 | }(); 193 | 194 | exports.default = ReactJsonSchema; 195 | 196 | /***/ }), 197 | /* 2 */ 198 | /***/ (function(module, exports, __webpack_require__) { 199 | 200 | "use strict"; 201 | 202 | 203 | /** 204 | * Copyright (c) 2015-present, Facebook, Inc. 205 | * 206 | * This source code is licensed under the MIT license found in the 207 | * LICENSE file in the root directory of this source tree. 208 | */ 209 | 210 | (function(f) { 211 | if (true) { 212 | module.exports = f(__webpack_require__(0)); 213 | /* global define */ 214 | } else if (typeof define === 'function' && define.amd) { 215 | define(['react'], f); 216 | } else { 217 | var g; 218 | if (typeof window !== 'undefined') { 219 | g = window; 220 | } else if (typeof global !== 'undefined') { 221 | g = global; 222 | } else if (typeof self !== 'undefined') { 223 | g = self; 224 | } else { 225 | g = this; 226 | } 227 | 228 | if (typeof g.React === 'undefined') { 229 | throw Error('React module should be required before ReactDOMFactories'); 230 | } 231 | 232 | g.ReactDOMFactories = f(g.React); 233 | } 234 | })(function(React) { 235 | /** 236 | * Create a factory that creates HTML tag elements. 237 | */ 238 | function createDOMFactory(type) { 239 | var factory = React.createElement.bind(null, type); 240 | // Expose the type on the factory and the prototype so that it can be 241 | // easily accessed on elements. E.g. `.type === Foo`. 242 | // This should not be named `constructor` since this may not be the function 243 | // that created the element, and it may not even be a constructor. 244 | factory.type = type; 245 | return factory; 246 | }; 247 | 248 | /** 249 | * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. 250 | */ 251 | var ReactDOMFactories = { 252 | a: createDOMFactory('a'), 253 | abbr: createDOMFactory('abbr'), 254 | address: createDOMFactory('address'), 255 | area: createDOMFactory('area'), 256 | article: createDOMFactory('article'), 257 | aside: createDOMFactory('aside'), 258 | audio: createDOMFactory('audio'), 259 | b: createDOMFactory('b'), 260 | base: createDOMFactory('base'), 261 | bdi: createDOMFactory('bdi'), 262 | bdo: createDOMFactory('bdo'), 263 | big: createDOMFactory('big'), 264 | blockquote: createDOMFactory('blockquote'), 265 | body: createDOMFactory('body'), 266 | br: createDOMFactory('br'), 267 | button: createDOMFactory('button'), 268 | canvas: createDOMFactory('canvas'), 269 | caption: createDOMFactory('caption'), 270 | cite: createDOMFactory('cite'), 271 | code: createDOMFactory('code'), 272 | col: createDOMFactory('col'), 273 | colgroup: createDOMFactory('colgroup'), 274 | data: createDOMFactory('data'), 275 | datalist: createDOMFactory('datalist'), 276 | dd: createDOMFactory('dd'), 277 | del: createDOMFactory('del'), 278 | details: createDOMFactory('details'), 279 | dfn: createDOMFactory('dfn'), 280 | dialog: createDOMFactory('dialog'), 281 | div: createDOMFactory('div'), 282 | dl: createDOMFactory('dl'), 283 | dt: createDOMFactory('dt'), 284 | em: createDOMFactory('em'), 285 | embed: createDOMFactory('embed'), 286 | fieldset: createDOMFactory('fieldset'), 287 | figcaption: createDOMFactory('figcaption'), 288 | figure: createDOMFactory('figure'), 289 | footer: createDOMFactory('footer'), 290 | form: createDOMFactory('form'), 291 | h1: createDOMFactory('h1'), 292 | h2: createDOMFactory('h2'), 293 | h3: createDOMFactory('h3'), 294 | h4: createDOMFactory('h4'), 295 | h5: createDOMFactory('h5'), 296 | h6: createDOMFactory('h6'), 297 | head: createDOMFactory('head'), 298 | header: createDOMFactory('header'), 299 | hgroup: createDOMFactory('hgroup'), 300 | hr: createDOMFactory('hr'), 301 | html: createDOMFactory('html'), 302 | i: createDOMFactory('i'), 303 | iframe: createDOMFactory('iframe'), 304 | img: createDOMFactory('img'), 305 | input: createDOMFactory('input'), 306 | ins: createDOMFactory('ins'), 307 | kbd: createDOMFactory('kbd'), 308 | keygen: createDOMFactory('keygen'), 309 | label: createDOMFactory('label'), 310 | legend: createDOMFactory('legend'), 311 | li: createDOMFactory('li'), 312 | link: createDOMFactory('link'), 313 | main: createDOMFactory('main'), 314 | map: createDOMFactory('map'), 315 | mark: createDOMFactory('mark'), 316 | menu: createDOMFactory('menu'), 317 | menuitem: createDOMFactory('menuitem'), 318 | meta: createDOMFactory('meta'), 319 | meter: createDOMFactory('meter'), 320 | nav: createDOMFactory('nav'), 321 | noscript: createDOMFactory('noscript'), 322 | object: createDOMFactory('object'), 323 | ol: createDOMFactory('ol'), 324 | optgroup: createDOMFactory('optgroup'), 325 | option: createDOMFactory('option'), 326 | output: createDOMFactory('output'), 327 | p: createDOMFactory('p'), 328 | param: createDOMFactory('param'), 329 | picture: createDOMFactory('picture'), 330 | pre: createDOMFactory('pre'), 331 | progress: createDOMFactory('progress'), 332 | q: createDOMFactory('q'), 333 | rp: createDOMFactory('rp'), 334 | rt: createDOMFactory('rt'), 335 | ruby: createDOMFactory('ruby'), 336 | s: createDOMFactory('s'), 337 | samp: createDOMFactory('samp'), 338 | script: createDOMFactory('script'), 339 | section: createDOMFactory('section'), 340 | select: createDOMFactory('select'), 341 | small: createDOMFactory('small'), 342 | source: createDOMFactory('source'), 343 | span: createDOMFactory('span'), 344 | strong: createDOMFactory('strong'), 345 | style: createDOMFactory('style'), 346 | sub: createDOMFactory('sub'), 347 | summary: createDOMFactory('summary'), 348 | sup: createDOMFactory('sup'), 349 | table: createDOMFactory('table'), 350 | tbody: createDOMFactory('tbody'), 351 | td: createDOMFactory('td'), 352 | textarea: createDOMFactory('textarea'), 353 | tfoot: createDOMFactory('tfoot'), 354 | th: createDOMFactory('th'), 355 | thead: createDOMFactory('thead'), 356 | time: createDOMFactory('time'), 357 | title: createDOMFactory('title'), 358 | tr: createDOMFactory('tr'), 359 | track: createDOMFactory('track'), 360 | u: createDOMFactory('u'), 361 | ul: createDOMFactory('ul'), 362 | var: createDOMFactory('var'), 363 | video: createDOMFactory('video'), 364 | wbr: createDOMFactory('wbr'), 365 | 366 | // SVG 367 | circle: createDOMFactory('circle'), 368 | clipPath: createDOMFactory('clipPath'), 369 | defs: createDOMFactory('defs'), 370 | ellipse: createDOMFactory('ellipse'), 371 | g: createDOMFactory('g'), 372 | image: createDOMFactory('image'), 373 | line: createDOMFactory('line'), 374 | linearGradient: createDOMFactory('linearGradient'), 375 | mask: createDOMFactory('mask'), 376 | path: createDOMFactory('path'), 377 | pattern: createDOMFactory('pattern'), 378 | polygon: createDOMFactory('polygon'), 379 | polyline: createDOMFactory('polyline'), 380 | radialGradient: createDOMFactory('radialGradient'), 381 | rect: createDOMFactory('rect'), 382 | stop: createDOMFactory('stop'), 383 | svg: createDOMFactory('svg'), 384 | text: createDOMFactory('text'), 385 | tspan: createDOMFactory('tspan'), 386 | }; 387 | 388 | // due to wrapper and conditionals at the top, this will either become 389 | // `module.exports ReactDOMFactories` if that is available, 390 | // otherwise it will be defined via `define(['react'], ReactDOMFactories)` 391 | // if that is available, 392 | // otherwise it will be defined as global variable. 393 | return ReactDOMFactories; 394 | }); 395 | 396 | 397 | 398 | /***/ }) 399 | /******/ ]); 400 | }); -------------------------------------------------------------------------------- /dist/react-json-schema.min.js: -------------------------------------------------------------------------------- 1 | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.ReactJsonSchema=t(require("react")):e.ReactJsonSchema=t(e.React)}("undefined"!=typeof self?self:this,function(e){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=1)}([function(t,n){t.exports=e},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r,o=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:[],n=[],r=0;return Object.keys(t).forEach(function(o){var a=t[o];a.key=void 0!==a.key?a.key:r,n.push(e.parseSchema(a)),r+=1}),n}},{key:"createComponent",value:function(e){e.component,e.children;var t=e.text,n=function(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}(e,["component","children","text"]),r=this.resolveComponent(e),o=void 0!==t?t:this.resolveComponentChildren(e);return(0,a.createElement)(r,n,o)}},{key:"resolveComponent",value:function(e){var t=this.getComponentMap(),n=null;if(!Object.prototype.hasOwnProperty.call(e,"component"))throw new Error("ReactJsonSchema could not resolve a component due to a missing component \n attribute in the schema.");return e.component===Object(e.component)?n=e.component:t&&t[e.component]?n=t[e.component]:Object.prototype.hasOwnProperty.call(c.default,e.component)&&(n=e.component),n}},{key:"resolveComponentChildren",value:function(e){return Object.prototype.hasOwnProperty.call(e,"children")?this.parseSchema(e.children):void 0}},{key:"getComponentMap",value:function(){return l.get(this)}},{key:"setComponentMap",value:function(e){l.set(this,e)}}]),e}();t.default=u},function(e,t,n){"use strict";var r;r=function(e){function t(t){var n=e.createElement.bind(null,t);return n.type=t,n}return{a:t("a"),abbr:t("abbr"),address:t("address"),area:t("area"),article:t("article"),aside:t("aside"),audio:t("audio"),b:t("b"),base:t("base"),bdi:t("bdi"),bdo:t("bdo"),big:t("big"),blockquote:t("blockquote"),body:t("body"),br:t("br"),button:t("button"),canvas:t("canvas"),caption:t("caption"),cite:t("cite"),code:t("code"),col:t("col"),colgroup:t("colgroup"),data:t("data"),datalist:t("datalist"),dd:t("dd"),del:t("del"),details:t("details"),dfn:t("dfn"),dialog:t("dialog"),div:t("div"),dl:t("dl"),dt:t("dt"),em:t("em"),embed:t("embed"),fieldset:t("fieldset"),figcaption:t("figcaption"),figure:t("figure"),footer:t("footer"),form:t("form"),h1:t("h1"),h2:t("h2"),h3:t("h3"),h4:t("h4"),h5:t("h5"),h6:t("h6"),head:t("head"),header:t("header"),hgroup:t("hgroup"),hr:t("hr"),html:t("html"),i:t("i"),iframe:t("iframe"),img:t("img"),input:t("input"),ins:t("ins"),kbd:t("kbd"),keygen:t("keygen"),label:t("label"),legend:t("legend"),li:t("li"),link:t("link"),main:t("main"),map:t("map"),mark:t("mark"),menu:t("menu"),menuitem:t("menuitem"),meta:t("meta"),meter:t("meter"),nav:t("nav"),noscript:t("noscript"),object:t("object"),ol:t("ol"),optgroup:t("optgroup"),option:t("option"),output:t("output"),p:t("p"),param:t("param"),picture:t("picture"),pre:t("pre"),progress:t("progress"),q:t("q"),rp:t("rp"),rt:t("rt"),ruby:t("ruby"),s:t("s"),samp:t("samp"),script:t("script"),section:t("section"),select:t("select"),small:t("small"),source:t("source"),span:t("span"),strong:t("strong"),style:t("style"),sub:t("sub"),summary:t("summary"),sup:t("sup"),table:t("table"),tbody:t("tbody"),td:t("td"),textarea:t("textarea"),tfoot:t("tfoot"),th:t("th"),thead:t("thead"),time:t("time"),title:t("title"),tr:t("tr"),track:t("track"),u:t("u"),ul:t("ul"),var:t("var"),video:t("video"),wbr:t("wbr"),circle:t("circle"),clipPath:t("clipPath"),defs:t("defs"),ellipse:t("ellipse"),g:t("g"),image:t("image"),line:t("line"),linearGradient:t("linearGradient"),mask:t("mask"),path:t("path"),pattern:t("pattern"),polygon:t("polygon"),polyline:t("polyline"),radialGradient:t("radialGradient"),rect:t("rect"),stop:t("stop"),svg:t("svg"),text:t("text"),tspan:t("tspan")}},e.exports=r(n(0))}])}); -------------------------------------------------------------------------------- /lib/ReactJsonSchema.js: -------------------------------------------------------------------------------- 1 | import { createElement } from 'react'; 2 | import DOM from 'react-dom-factories'; 3 | 4 | const componentMapCollection = new WeakMap(); 5 | 6 | export default class ReactJsonSchema { 7 | parseSchema(schema) { 8 | let element = null; 9 | let elements = null; 10 | if (Array.isArray(schema)) { 11 | elements = this.parseSubSchemas(schema); 12 | } else if (schema) { 13 | element = this.createComponent(schema); 14 | } 15 | return element || elements; 16 | } 17 | 18 | parseSubSchemas(subSchemas = []) { 19 | const Components = []; 20 | let index = 0; 21 | Object.keys(subSchemas).forEach((key) => { 22 | const subSchema = subSchemas[key]; 23 | subSchema.key = typeof subSchema.key !== 'undefined' ? subSchema.key : index; 24 | Components.push(this.parseSchema(subSchema)); 25 | index += 1; 26 | }); 27 | return Components; 28 | } 29 | 30 | createComponent(schema) { 31 | // eslint-disable-next-line no-unused-vars 32 | const { component, children, text, ...rest } = schema; 33 | const Component = this.resolveComponent(schema); 34 | const Children = typeof text !== 'undefined' ? text : this.resolveComponentChildren(schema); 35 | return createElement(Component, rest, Children); 36 | } 37 | 38 | resolveComponent(schema) { 39 | const componentMap = this.getComponentMap(); 40 | let Component = null; 41 | if (Object.prototype.hasOwnProperty.call(schema, 'component')) { 42 | if (schema.component === Object(schema.component)) { 43 | Component = schema.component; 44 | } else if (componentMap && componentMap[schema.component]) { 45 | Component = componentMap[schema.component]; 46 | } else if (Object.prototype.hasOwnProperty.call(DOM, schema.component)) { 47 | Component = schema.component; 48 | } 49 | } else { 50 | throw new Error(`ReactJsonSchema could not resolve a component due to a missing component 51 | attribute in the schema.`); 52 | } 53 | return Component; 54 | } 55 | 56 | resolveComponentChildren(schema) { 57 | return (Object.prototype.hasOwnProperty.call(schema, 'children')) ? 58 | this.parseSchema(schema.children) : undefined; 59 | } 60 | 61 | getComponentMap() { 62 | return componentMapCollection.get(this); 63 | } 64 | 65 | setComponentMap(componentMap) { 66 | componentMapCollection.set(this, componentMap); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-json-schema", 3 | "version": "1.2.2", 4 | "description": "Write component schema in JSON; parse to create react elements.", 5 | "keywords": [ 6 | "react", 7 | "JSON", 8 | "schema", 9 | "components" 10 | ], 11 | "author": { 12 | "name": "A collaborative project overseen by Club OS", 13 | "url": "https://club-os.com/" 14 | }, 15 | "repository": { 16 | "type": "git", 17 | "url": "https://github.com/TechniqueSoftware/react-json-schema" 18 | }, 19 | "license": "Apache-2.0", 20 | "bugs": { 21 | "url": "https://github.com/TechniqueSoftware/react-json-schema/issues" 22 | }, 23 | "scripts": { 24 | "build": "eslint lib/ReactJsonSchema.js && webpack --progress --profile --colors --config webpack.config.dist.js", 25 | "jasmine": "eslint lib/ReactJsonSchema.js && jasmine spec/spec.js", 26 | "pretest": "eslint lib/ReactJsonSchema.js && webpack --progress --profile --colors --config webpack.config.spec.js", 27 | "test": "npm run jasmine", 28 | "preversion": "npm run jasmine", 29 | "version": "npm run build && git add -A", 30 | "postversion": "git push origin master && git push origin --tags" 31 | }, 32 | "main": "dist/react-json-schema.js", 33 | "files": [ 34 | "lib", 35 | "dist" 36 | ], 37 | "engines": { 38 | "node": ">=6.4.0" 39 | }, 40 | "peerDependencies": { 41 | "react": ">=15" 42 | }, 43 | "devDependencies": { 44 | "babel-core": "^6.26.3", 45 | "babel-eslint": "^8.2.1", 46 | "babel-loader": "^7.1.2", 47 | "babel-plugin-transform-es2015-destructuring": "^6.23.0", 48 | "babel-plugin-transform-object-rest-spread": "^6.26.0", 49 | "babel-preset-env": "^1.7.0", 50 | "babel-preset-react": "^6.24.1", 51 | "clean-webpack-plugin": "^0.1.18", 52 | "eslint": "^4.17.0", 53 | "eslint-config-airbnb": "^16.1.0", 54 | "eslint-plugin-import": "^2.8.0", 55 | "eslint-plugin-jsx-a11y": "^6.0.3", 56 | "eslint-plugin-react": "^7.6.1", 57 | "jasmine": "^2.99.0", 58 | "path": "^0.12.7", 59 | "react": "^16.2.0", 60 | "uglifyjs-webpack-plugin": "^1.2.5", 61 | "webpack": "^3.11.0" 62 | }, 63 | "dependencies": { 64 | "react-dom-factories": "^1.0.2" 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /spec/ReactJsonSchemaSpec.js: -------------------------------------------------------------------------------- 1 | /* global jasmine, beforeEach, describe, it, expect, spyOn */ 2 | /* eslint max-len: 0 */ 3 | 4 | import React from 'react'; 5 | import ReactJsonSchema from '../lib/ReactJsonSchema'; 6 | 7 | let reactJsonSchema; 8 | let schema; 9 | 10 | export default describe('ReactJsonSchema', () => { 11 | class Tester extends React.Component { // eslint-disable-line 12 | render() { 13 | React.createElement('h1', null, 'Tester!!!!'); 14 | } 15 | } 16 | 17 | beforeEach(() => { 18 | reactJsonSchema = new ReactJsonSchema(); 19 | /* eslint-disable */ 20 | schema = { 21 | "component": Tester, 22 | "someProp": "I'm a tester" 23 | }; 24 | /* eslint-enable */ 25 | }); 26 | describe('when parsing schema', () => { 27 | it('should allow children to have a null value', () => { 28 | const component = reactJsonSchema.parseSchema({ component: 'input', children: null, value: 'test' }); 29 | expect(React.isValidElement()).toBe(true); 30 | }); 31 | 32 | it('should return an array of React elements when schema\'s root type is of type array.', () => { 33 | const actual = reactJsonSchema.parseSchema([schema]); 34 | expect(Array.isArray(actual)).toBe(true); 35 | const component = actual[0]; 36 | expect(React.isValidElement()).toBe(true); 37 | }); 38 | it('should return a root React element when the schema\'s root type is of type object.', () => { 39 | const actual = reactJsonSchema.parseSchema(schema); 40 | expect(actual === Object(actual)).toBe(true); 41 | }); 42 | }); 43 | describe('when parsing sub-schemas', () => { 44 | it('should return an empty array when no schemas are passed as an argument.', () => { 45 | const actual = reactJsonSchema.parseSubSchemas(); 46 | expect(Array.isArray(actual)).toBe(true); 47 | }); 48 | it('should return an array of React elements when valid schemas are passed as an argument.', () => { 49 | const subSchemas = [schema, schema]; 50 | const actual = reactJsonSchema.parseSubSchemas(subSchemas); 51 | expect(!!actual.length).toBe(true); 52 | expect(actual[0] === Object(actual[0])).toBe(true); 53 | }); 54 | it('should construct sub-schema React elements by parsing each sub-schema.', () => { 55 | const subSchemas = [schema, schema]; 56 | spyOn(reactJsonSchema, 'parseSchema'); 57 | reactJsonSchema.parseSubSchemas(subSchemas); 58 | expect(reactJsonSchema.parseSchema).toHaveBeenCalled(); 59 | }); 60 | it('should consume a key defined in the schema\'s keys for the current sub-schema based on the current sub-schema\'s index to meet React\'s key expectation of multiple React elements.', () => { 61 | const subSchemas = [Object.assign({}, schema), Object.assign({}, schema)]; 62 | for (const subSchema of subSchemas) { subSchema.key = Math.random(); } 63 | spyOn(reactJsonSchema, 'parseSchema'); 64 | reactJsonSchema.parseSubSchemas(subSchemas); 65 | expect(reactJsonSchema.parseSchema).toHaveBeenCalledWith(subSchemas[0]); 66 | expect(reactJsonSchema.parseSchema).toHaveBeenCalledWith(subSchemas[1]); 67 | }); 68 | it('should assign a key to the current sub-schema based on the current sub-schema\'s index to meet React\'s key expectation of multiple React elements.', () => { 69 | spyOn(reactJsonSchema, 'parseSchema'); 70 | const subSchemas = [Object.assign({}, schema), Object.assign({}, schema)]; 71 | reactJsonSchema.parseSubSchemas(subSchemas); 72 | const firstSubSchema = Object.assign({}, subSchemas[0], { key: 0 }); 73 | const secondSubSchema = Object.assign({}, subSchemas[1], { key: 1 }); 74 | expect(reactJsonSchema.parseSchema).toHaveBeenCalledWith(firstSubSchema); 75 | expect(reactJsonSchema.parseSchema).toHaveBeenCalledWith(secondSubSchema); 76 | }); 77 | }); 78 | describe('when creating components', () => { 79 | it('should throw an error when no schema is passed as an argument.', () => { 80 | spyOn(reactJsonSchema, 'resolveComponent'); 81 | spyOn(reactJsonSchema, 'resolveComponentChildren'); 82 | reactJsonSchema.resolveComponent.and.returnValue(null); 83 | reactJsonSchema.resolveComponentChildren.and.returnValue(null); 84 | expect(reactJsonSchema.createComponent).toThrowError(); 85 | }); 86 | it('should create a React element.', () => { 87 | const actual = reactJsonSchema.createComponent(schema); 88 | expect(React.isValidElement()).toBe(true); 89 | }); 90 | it('should resolve and pass props (schema key value pair not described by component or children) and child elements to React\'s create element functionality.', () => { 91 | const largeSchema = Object.assign({}, schema); 92 | largeSchema.children = [schema]; 93 | spyOn(React, 'createElement'); 94 | reactJsonSchema.createComponent(largeSchema); 95 | expect(React.createElement).toHaveBeenCalledWith(jasmine.any(Function), { someProp: schema.someProp }, jasmine.any(Array)); 96 | }); 97 | }); 98 | describe('when resolving components (evaluating schema for mapping requirements)', () => { 99 | it('should throw an error when a schema element does not have a component attribute.', () => { 100 | expect(reactJsonSchema.resolveComponent).toThrowError(); 101 | }); 102 | it('should resolve components defined as strings against a component map.', () => { 103 | const stringSchema = { component: 'Tester' }; 104 | reactJsonSchema.setComponentMap({ Tester }); 105 | const actual = reactJsonSchema.resolveComponent(stringSchema); 106 | expect(React.isValidElement()).toBe(true); 107 | }); 108 | it('should resolve components defined as components without a component map.', () => { 109 | reactJsonSchema.setComponentMap({}); // a little unecessary, but to paint the picture 110 | const actual = reactJsonSchema.resolveComponent(schema); 111 | expect(React.isValidElement()).toBe(true); 112 | }); 113 | it('should resolve native HTML tags.', () => { 114 | spyOn(React, 'createElement'); 115 | const stringSchema = { component: 'h1' }; 116 | reactJsonSchema.parseSchema(stringSchema); 117 | expect(React.createElement).toHaveBeenCalledWith(stringSchema.component, jasmine.any(Object), undefined); 118 | }); 119 | }); 120 | describe('when resolving component children', () => { 121 | it('should resolve text before resolving child components.', () => { 122 | spyOn(React, 'createElement'); 123 | spyOn(reactJsonSchema, 'resolveComponentChildren'); 124 | const stringSchema = { component: 'h1', text: 'Hello World' }; 125 | reactJsonSchema.parseSchema(stringSchema); 126 | expect(React.createElement).toHaveBeenCalledWith(jasmine.any(String), jasmine.any(Object), stringSchema.text); 127 | expect(reactJsonSchema.resolveComponentChildren).not.toHaveBeenCalled(); 128 | }); 129 | it('should return undefined if no child components are present.', () => { 130 | const actual = reactJsonSchema.resolveComponentChildren(schema); 131 | expect(typeof actual === 'undefined').toBe(true); 132 | }); 133 | it('should return an array with child components if the children attribute is defined by valid sub-schemas.', () => { 134 | const largeSchema = Object.assign({}, schema); 135 | largeSchema.children = [schema]; 136 | const actual = reactJsonSchema.resolveComponentChildren(largeSchema); 137 | expect(Array.isArray(actual)).toBe(true); 138 | expect(!!actual.length).toBe(true); 139 | }); 140 | }); 141 | describe('when multiple instances of ReactJsonSchema are created with different componentMaps', () => { 142 | it('getComponentMap() should return the appropriate value for each instance', () => { 143 | const reactJsonSchema1 = new ReactJsonSchema(); 144 | const componentMap1 = { component1: Tester }; 145 | reactJsonSchema1.setComponentMap(componentMap1); 146 | const reactJsonSchema2 = new ReactJsonSchema(); 147 | const componentMap2 = { component2: Tester }; 148 | reactJsonSchema2.setComponentMap(componentMap2); 149 | expect(reactJsonSchema1.getComponentMap()).toEqual(componentMap1); 150 | expect(reactJsonSchema2.getComponentMap()).toEqual(componentMap2); 151 | }); 152 | }); 153 | }); 154 | -------------------------------------------------------------------------------- /spec/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Jasmine Spec Runner 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /spec/spec.entry.js: -------------------------------------------------------------------------------- 1 | export * from './ReactJsonSchemaSpec.js'; 2 | -------------------------------------------------------------------------------- /spec/support/jasmine.json: -------------------------------------------------------------------------------- 1 | { 2 | "spec_dir": "spec", 3 | "spec_files": [ 4 | "**/*[sS]pec.js" 5 | ], 6 | "helpers": [ 7 | "helpers/**/*.js" 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /webpack.config.dist.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const CleanWebpackPlugin = require('clean-webpack-plugin'); 3 | const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); 4 | const reactJsonSchema = path.join(__dirname, './lib/ReactJsonSchema.js'); 5 | const distPath = path.join(__dirname, './dist'); 6 | 7 | module.exports = { 8 | entry: { 9 | 'react-json-schema': reactJsonSchema, 10 | 'react-json-schema.min': reactJsonSchema, 11 | }, 12 | output: { 13 | library: 'ReactJsonSchema', 14 | libraryTarget: 'umd', 15 | path: distPath, 16 | filename: '[name].js' 17 | }, 18 | module: { 19 | rules: [ 20 | { 21 | test: /\.js$/, 22 | include: /lib/, 23 | exclude: /node_modules/, 24 | use: [{ 25 | loader: 'babel-loader', 26 | options: { 27 | presets: ['react', 'env'], 28 | plugins: ['transform-es2015-destructuring', 'transform-object-rest-spread'] 29 | } 30 | }] 31 | } 32 | ] 33 | }, 34 | externals: { 35 | react: { 36 | root: 'React', 37 | commonjs2: 'react', 38 | commonjs: 'react', 39 | amd: 'react' 40 | } 41 | }, 42 | resolve: { 43 | modules: [ 44 | path.join(__dirname, 'lib'), 45 | 'node_modules' 46 | ] 47 | }, 48 | plugins: [ 49 | new CleanWebpackPlugin(distPath), 50 | new UglifyJsPlugin({ 51 | include: /\.min\.js$/ 52 | }) 53 | ] 54 | }; 55 | -------------------------------------------------------------------------------- /webpack.config.spec.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const srcPath = path.join(__dirname, './spec'); 3 | 4 | module.exports = { 5 | entry: path.join(srcPath, 'spec.entry'), 6 | output: { 7 | path: srcPath, 8 | filename: 'spec.js' 9 | }, 10 | module: { 11 | rules: [ 12 | { 13 | test: /\.js$/, 14 | exclude: /node_modules/, 15 | use: [{ 16 | loader: 'babel-loader', 17 | options: { 18 | presets: ['react', 'env'], 19 | plugins: ['transform-es2015-destructuring', 'transform-object-rest-spread'] 20 | } 21 | }] 22 | } 23 | ] 24 | }, 25 | resolve: { 26 | modules: [ 27 | path.join(__dirname, 'spec'), 28 | path.join(__dirname, 'lib'), 29 | 'node_modules' 30 | ] 31 | } 32 | }; 33 | --------------------------------------------------------------------------------