简体   繁体   中英

Rendering react components using json schema

I am trying to render React component dynamically using JSON. My folder structure is like this:

components
   Foo.jsx
   Bar.jsx
   index.js
App.jsx

In index.js , I am exporting all the components as strings so that I can use them to render in App.jsx . It looks like this:

import Foo from './Foo'
import Bar from './Bar'

export default {
  'FOO': Foo,
  'BAR': Bar
}

My App.jsx looks like this:

import React from 'react'
import ComponentsMap from './components'

const json = {'type': 'BAR', props: {}} 
const App = () => {
   const ComponentToRender = ComponentsMap[json.type]
   return (
      <ComponentToRender {...json.props} />
   )
}

In my approach, every time I add a new component I have to export it in index.js as well. Is there any other alternative way to do it?

Try wildcard plugin of babel. It will import all files exists in a directory. Then you don't need index.jsx, import all components via * inside App.jsx.

https://www.npmjs.com/package/babel-plugin-wildcard

Hope this can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM