Declare your React component tree in JSON
react-from-json lets you render React
<Burger ="Wahlburger"><Patty ="impossible" /></Burger>
It also supports non-recursive structures.
npm install --save react-from-json
import React from "react";import ReactFromJSON from "react-from-json";const entry =type: "Burger"props:chain: "Wahlburger"children:type: "Patty"props:variant: "Impossible";const mapping =<div><h1>chain</h1><div>children</div></div><span>variant</span>;const Example =return <ReactFromJSON = = />;;
Props passed to your components
Props passed to your mapped components include
propKey- name of the prop that rendered your component
propIndex- index of your component if using flat trees
typevalue for your component
...props- the resolved value of your
propsobject, with relevant child nodes rendered as components
Other JSON shapes
If your data doesn't follow the
react-from-json makes it easy to map your data on the fly using the
import React from "react";import ReactFromJSON from "react-from-json";import mapping from "./mapping";const entryWithDifferentShape =_type: "Burger"chain: "Wahlburger"children:_type: "Patty"variant: "Impossible";const mapProp = propif prop_typeconst _type ...props = prop;returntype: _typeprops;return prop;;const Example =return<ReactFromJSON===/>;;
react-from-json also supports flat, non-recursive structures via the special
<ComponentLookup /> component. This is useful when working with typed systems like GraphQL, and you need to avoid unions.
<ComponentLookup /> component
<ComponentLookup /> simply maps to another component defined in a
components object. If you were using it in React, you would use it like:
<ComponentLookup ="Button" = />
which would look up the
Button component at index
0 in the
components object, resolving to:
<Button =>Hello World!</Button>
react-from-json we use JSON, so we would write this:
idhere is set by the
componentIndex, since we didn't specify one in the JSON. See this comment on IDs for more information.
Here's the same example as above, instead using a
<ComponentLookup /> for
entry.props.patty, and providing a separate
import React from "react";import ReactFromJSON from "react-from-json";const entry =type: "Burger"props:chain: "Wahlburger"patty:type: "ComponentLookup"props:componentIndex: 0componentType: "Patty";const mapping =<div><h1>chain</h1><div>patty</div></div><span>variant</span>;const components =Patty:type: "Patty"props:variant: "Impossible";const Example =return<ReactFromJSON = = = />;;
A note on ids
react-from-json will map
id from the root of your component JSON to the React component's
id prop. Likewise, if you specify
props, it will use this. If you use the
<ComponentLookup /> component,
react-from-json will use the array index as
id unless another
id is specified. Your
id will always take priority.
react-from-json supports generic types for use with TypeScript.
MIT © Measured Co.