Friday, April 20, 2018

Render React Native Elements from JSON

Leave a Comment

I have searched around...can't quite find what I'm looking for, so I appreciate any help! Here is what I am going for:

I am building a CMS-like setup for a React Native app. This is so that an admin of an app can login to the CMS dashboard, and update a page/view of the app without having to go into the hardcode. I would like them to be able to choose from a pre-set list of components and be able to drag-and-drop them into the app, in whatever order they would want and be able to update the content and colors, etc. Let me provide an example...

There is a home page that I imagine having a rotating banner at the top, then a button for a information modal, then a set of menu links to go to sub-child pages.

So what I think, development-wise, is to give the app admin a WYSIWYG type of setup, and to store the result of this in the Database. It could store in the database as:

<RotatingBanner /> <Modal /> <ContentMenu>     <ContentMenuLink title="About" />     <ContentMenuLink title="Competitive" />     <ContentMenuLink title="Recreational" />     <ContentMenuLink title="Tournaments" /> <ContentMenu /> 

Right now, when I try to render this into a screen, I continue to have it render that as the actual words vs the components they are representing if that makes sense. So the page looks just like the code block above, instead of seeing a rotating banner and modal, etc.

I have tried a tool to convert HTML into React Native elements...does anyone know how I can convert a fetched JSON that would look like:

{content: "<RotatingBanner /><Modal /><ContentMenu>...."} 

and have it create the real components in the render function? Any other thoughts or ideas/advice on creating a CMS like this are greatly appreciated if you would like.

Thanks!

2 Answers

Answers 1

Let's say your have this JSON:

const data = {   "components": [     {"name": "component1", props: {"hello": "world"}},     {"name": "component2", props: {"color": "red"}},   ] } 

Make your components and then reference them in an Object (map):

import Component1 from './Component1' import Component2 from './Component2'  const COMPONENT_MAP = {   component1: Component1,   component2: Component2, } 

Then make your wrapper component:

const Wrapper = ({data}) => (   <View>     {data.components.map(({name, props}) => {       const Component = COMPONENT_MAP[name]       return <Component {...props} />     }}   </View> ) 

Voilà :)

<Wrapper data={data} /> 

Answers 2

I would recommend using Array's to save and render multiple childrens

const Component1 = () => <Text>One</Text> const Component2 = () => <Text>One</Text>  const childs = [   Component1,   Component2 ] return childs 

React is able to render arrays as they are. Other possible solution could be,

return Object.keys(child).map(item => childs[item] ) 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment