Code Monkey home page Code Monkey logo

react-json-schema's Introduction

react-json-schema

npm install react-json-schema

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.

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.

Quick Documentation and Examples

Full Documentation

Schema

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:

  • component: MUST exist and be defined by a string or React component (must be a string if describing a native HTML tag)
  • children: MAY exist to define sub-components
  • text: MAY exist to as a string to define inner HTML text (overrides children)
  • key: MAY exist to define a key for dynamic children

Example JSON schema

const schema = {
  "component": "CommentList",
  "children": [
    {
      "component": "Comment",
      "author": "Pete Hunt",
      "children": "This is one comment"
    },
    {
      "component": "Comment",
      "author": "Jordan Walke",
      "children": "This is *another* comment"
    },
    {
      "component": "a",
      "href": "#help",
      "text": "I need help"
    }
  ]
};

Example JS literal

...
  {
    "component": Comment,
    "author": "Pete Hunt",
    "children": "This is one comment"
  },
...
Dynamic Children and Keys

When arrays of components exist (like children), react-json-schema will resolve a key for the element, which follows the rules for dynamic children. It will either use a custom key if defined, or resolve a numeric key based on the array index.

Example of defining child keys

...
  {
    "component": "Comment",
    "key": "0ab19f8e", // defined key
    "author": "Pete Hunt",
    "children": "This is one comment"
  },
...

Component Mapping

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.

Example for exposing non-exposed components (ES6)

/* es6 object literal shorthand: { ContactForm } == { ContactForm: ContactForm } */
contactForm.setComponentMap({ ContactForm, StringField });

Parsing

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.

Example (ES6)

ReactDOM.render(contactForm.parseSchema(schema),
  document.getElementById('contact-form'));

Complete Example

import ReactDOM from 'react-dom';
import ReactJsonSchema from 'react-json-schema';

import FormStore from 'FormStore';
import CommentList from 'CommentList';
import Comment from 'Comment';

// For this example, let's pretend I already have data and am ignorant of actions
const schema = FormStore.getFormSchema();
const view = new ReactJsonSchema();

view.setComponentMap({ CommentList, Comment });

ReactDOM.render(view.parseSchema(schema),
  document.getElementById('content'));

Demo an Example Codebase

To run the demo

Contribution and Code of Conduct

If you'd like to ask a question, raise a concern, or contribute, please follow our contribution guidelines.

Alternatives

  • 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.

Roadmap

  • Playground on our public site for discoverability
  • Possibility of react-native-json-schema

react-json-schema's People

Contributors

eiof avatar iamdustan avatar nlaffey avatar sirajul147 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-json-schema's Issues

Support private key for metadata

I'd like to be able to support a private key that could hold implementation specific details that aren't necessarily relevant for the final rendered state of the schema. An example would be that it would be convenient for updating the schema if every element had some type of internal id that we could map to. This wouldn't be the same as the key prop because it's not a key for dynamic children, but a special identifier to get straight to the component in the schema. I don't want every component I render to have an ID prop, so having a place to store implementation specific details like that, where they won't be included in the final render would be nice.

I was thinking something like this

component : 'MyComponent',
'@meta' : {
  id: 'root',
}

which would render to this

<MyComponent />

Support for React 0.14

React 0.14 should be supported, and if not included, rollback to 0.13. This will allow ReactDOM.render to work without giving a conflicting version error message. I don't know enough about React Native to know if there is any implementation details that apply under 0.14 as well, or if this library is even applicable.

Doesnt work with React 16

@nlaffey @eiof
The library no longer works with React 16. It is using DOM component from 'react', which is no longer available. It should be repaced with react-dom-factories.
Also the library is refering to the React.createClass, which was deprecated in React 15 and removed from React 16.

This has been updated in the PR #22. Would be great if someone could review the same.

Plugin Support

React-json-schema is intentionally minimal. It's purpose is to create React elements from JSON, and does not support configurations beyond this scope. However, there's an opportunity to define configuration beside component definitions (#24, #32, #33). Providing plugin support in react-json-schema will allow users to customize their react-json-schema implementation, and keep the core library small.

The thought is that plugins would be capable of modifying each subSchema before element creation.

We could migrate to a monorepo (using Lerna) so that all plugins are housed in the same repository, which is common for open source JavaScript (webpack, babel, etc.).

I'm personally exploring what this would look like. I'm open to suggestions.

Address React Warnings

Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

Warning: Uncontrolled(Dropdown): React.createClass is deprecated and will be removed in version 16. Use plain JavaScript classes instead. If you're not yet ready to migrate, create-react-class is available on npm as a drop-in replacement.

Mapping fails

Hi,

I am using your nice plugin with a lot of satisfaction!

There is one issue when it comes to map an object literal using a pre-definite schema.

This is the required component structure:
const steps =
[
{name: 'Step 1', component: },
{name: 'Step 2', component: },
{name: 'Step 3', component: },
{name: 'Step 4', component: },
{name: 'Step 5', component: }
]

<div className='step-progress'>
    <StepZilla steps={steps}/>
</div>

I have tried to map it via following schema, but the Reference component is expecting an object literal with the following structure:

  • {name: 'Step 1', component: },

The issue is in the children part as this in not an object like expected. I have tried just using:

  • "component": "AxQlikVisualization" but it give sme
    Failed prop type: Invalid prop steps[0].component of type string supplied to StepZilla,

I am sure I miss out something...

{
"component": "Container",
"className": "Wizard",
"children": [
{
"component": "AxStepWizard",
"steps": [
{
"name": "Step 1",
**"children": [
{
"component": "AxQlikVisualization"

                    }
                ]**
            }
        ]
    }
]

}

Can you please assist me in this?

Thanks and regards,
Patric

Demo example not working!!!

I was trying to run your demo example, but it is not working post following your instructions. Could you please elaborate the configuration process bit more since I also feel I might be missing something. You can check the below image which is being displayed after making sure all the dependencies have been installed.
image

TypeError: Cannot read property 'hasOwnProperty' of undefined

When I use this schema I get this error:
TypeError: Cannot read property 'hasOwnProperty' of undefined

Same happens when I use other HTML natives like 'div', but my custom components work fine as JS literals. Am I doing something wrong?

    const hey = new ReactJsonSchema();

   const schema = {
        'component': "form",
        'children': [ 
            {
                'component': Row,
                'children': [
                    {
                    'component': Input,
                    'inColumn': true,
                    'label': 'What\'s your name',
                    'name': 'fullname',
                    'value': 'testing'
                    },
                    {
                    'component': Input,
                    'inColumn': true,
                    'label': 'hey',
                    'name': 'hey',
                    'value': 'hello'
                    }
                ],
            }
        ]
    }

     {hey.parseSchema(schema)}

Passing handler function as props

@nlaffey @eiof
Does the current implementation support passing handler functions as function names to the schema?

I'm able to work with the below scenario:

{
    component: 'MyComponent,
    onClick: this.handleClickingMe.bind(this),
}

This one is possible if I'm creating using the schema just within the Component.

But it is not working with the below scenario, where I'd like to save and load the schema from the DB. In such cases, it is not possible to put the function reference directly, it would require function names to be saved instead.

{
    component: 'MyComponent,
    onClick: 'handleClickingMe',
}

I'd suggest something like below:

{
    component: 'MyComponent,
    handlers: [
            onClick: 'handleClickingMe',
    ]

}

Would be good if you could throw some insights on this. I'll find time to contribute for the same.

Improve component resolution

See #42 (comment) for context.

  • Remove react-dom-factories from dependencies - users can set components from react-dom-factories using ReactJsonSchema.setComponentMap
  • Write tests for setting components from DOM from react-dom-factories, and for elements from React Native
  • Remove README bullet point for investigating React Native support

React Router is not able pass params into component created by this library

@elliottisonfire
JSON,
{
"component": "ActionForm",
"title": "Action Comment",
"columnUnit": 12,
"styles": "",
"children": [
{
"component": "Dropdown",
"label": "Reason",
"name": "Reason",
"dropdown_content": ["Unable to verify identity/Entity (L2)", "Unable to verify identity/Entity (L3)"],
"styles": ""
},
{
"component": "CheckboxField",
"styles": {
"margin": "10px"
},
"checkboxes": [
{
"label": "checkbox_item1_checked_default",
"key": 0
},
{
"label": "Possible Name Match",
"key": 1
},
{
"label": "Possible Business Name Match",
"key": 2
},
{
"label": "Physical Address Matches",
"key": 3
}
]
}
]
}

......
const componentMap = {
ActionForm,
Dropdown,
CheckboxField
}
const form = new ReactJsonSchema();
form.setComponentMap(componentMap);
const ActionFormComponent = () => form.parseSchema(actionFormSchema);

....

       <Route path="action/:actionId" component={ActionFormComponent} />

uniforms library not supported

i want to pass a component to react json schema which is the imported from uniforms bootstrap4 this is the library for json forms i want to passs this component to react json schema like that
import AutoForm from 'uniforms-bootstrap4/AutoForm';
but when i am passing this to children it didn't render anything

`const schema = {
component: 'div',
children:[{
component:'AutoForm',
props: {
// validate:"onSubmit",
schema:loginSchema,
// onSubmit:(docs) =>{console.log('submit')},
// placeholder:true,
// label:true
},
}]

};

and here is my login schema

`const loginSchema = new SimpleSchema({
email: {
type: String,
max: 50,
regEx: SimpleSchema.RegEx.Email,
uniforms:{
placeholder:'Email',label:false,
type: 'email'
}
},
password:
{
type: String,
max: 100,
uniforms: {type: 'password',
placeholder:'Password',label:false

  }
  },

Remember: {
type: Boolean,
label:'Remember me',
defaultValue: false,
optional:true,
uniforms: {type: 'password',
placeholder:'Password',

}

},
});`
export default () => parseJsonSchema(schema);

other components are rendering but not this one

Need Json file validator for Gulp

We have bunch of JSON files which uses react-json-schema parser to parseSchema and render. We want to build Gulp task or any validator to validate the JSON files during build time.

UMD Distribution Option

Currently, the ReactJsonSchema distribution has to be used in a CommonJS capable environment. It may serve someone benefit for there to be a UMD distribution of ReactJsonSchema.

UMD = Universal Module Definition

These are modules which are capable of working everywhere, be it in the client, on the server or elsewhere.
(https://github.com/umdjs/umd)

I propose we add a the UMD distribution under a new directory, dist/umd. Weback is capable of outputting the additional distribution at build time.

React Native support

What sort of level of effort are we talking about to enhance react-json-schema to support React Native usage? Would it even be possible to work in the native app component world as opposed to the DOM world?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.