react-json-renderer
Basic converter of a React component tree to a JS object or JSON string and associated renderer using provided components.
Installation
yarn add react-json-renderer # Yarn npm install react-json-renderer # npm
React is a required peer dependency, make sure to install it as well if you haven't already:
yarn add react # Yarn npm install react # npm
APIs
convertToObject
: Object
Converts a component tree to a formatted Object supported by the renderFromObject()
function.
convertToJSON
: Object
Converts a component tree to a JSON string supported by the Renderer
component.
renderFromObject
: ReactElement<*>
Converts a formatted Object to a React elements tree ready to be rendered by React.
Components
Renderer
Props:
json?: string
: Formatted Object tree in JSON.tree?: Object
: Formatted Object tree.
Example
Server or other source
// Simple strings will be exported as component types and functions will be executedconst Text = 'Text'const View = 'View'const Welcome = <View> <Text>Welcome name!</Text> </View> // Returns the JSON payload to provide to the clientconst createWelcome =
Web client
// Components from the payload supported by the clientconst components = <span className='text'>children</span> <div className='view'>children</div> // Fallback for unsupported components, if not provided it will return null and therefore not render the component and its childrenconst Fallback = <div className='fallback'>children</div> // Inject the JSON payload from the server and render with provided component and fallbackconst PayloadRenderer = <Renderer components=components fallback=Fallback json=payload />
React-Native client
const styles = StyleSheet const RenderText = <Text style=stylestext>children</Text>const RenderView = <View style=stylesview>children</View>const components = Text: RenderText View: RenderView const PayloadRenderer = <Renderer components=components fallback=RenderView json=payload />
License
MIT
See LICENSE file.