A component that can be built based on specifically formatted JSON
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
build
react-json-component-sample
src
.babelrc
.gitignore
README.md
package-lock.json
package.json
webpack.config.js
yarn.lock

README.md

react-json-component

Inspired by this tweet

Usage

import React from 'react';
import ReactDOM from 'react-dom';
import JSONComponent from 'react-json-component';

const componentJson = {
  type:"span",
  props:{
    style:{
      backgroundColor:"#0000ff"
    }
  },
  children:"This is a cool JSON component"
};

ReactDOM.render(<JSONComponent jsonSrc={componentJson} />, document.getElementById('root'));

Props

{
  jsonSrc: Object
  componentMap: Object
}

JSON Properties

{
  type: String | Function
  props: Object
  children: String | Array | Function
}

componentMap

componentMap is a way to match strings to components. You can define type to be a custom React Component if you create the componentMap in JS to relate the string to the actual component function or class.

Example

component.json
{
  "type":'TableComponent' // this is a string, since we can't put functions / classes in JSON!
  "props":{
    // ... props here
    "data":[
      // ... table data
    ]
  }
}
TableComponent.js
import React from 'react';

export default (props) => (
  <table>
    // ... render props.data here
  </table>
)
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import TableComponent from './TableComponent';
import JSONComponent from './JSONComponent';

import jsonSrc from 'component.json';

const props = { jsonSrc, componentMap:{ TableComponent } };
ReactDOM.render(<JSONComponent {...props} />, document.getElementById('root'));

Examples

Check out the sample app (scaffolded with Create React App):

  1. cd react-json-component
    • If react-json-component isn't already available in node-modules
      1. npm link
      2. cd react-json-component-sample
      3. npm link react-json-component
  2. yarn install
  3. yarn start

View ./react-json-component-sample/src/index.js for a number of different ways to define your component object (in JS and JSON)

Why?

Because I am not a coward.