Creating components based on data received from server/database

Viewed 48

I'm trying to create a blog feed that is generated from a data set acquired from a server/file so far I have created a component to render the data but the source I've used, uses basic HTML components where I use another framework called CoreUI to wrap my data with.

Here's the rendering component:

import { CardCreator } from './customComponent/CardCreator'
import { createElement } from 'react'
import { CustomHeader } from './customComponent/CustomHeader'
import { CustomCardBody } from './customComponent/CustomCardBody'
import { CustomCardFooter } from './customComponent/CustomCardFooter'


const keysToComponentMap = {
  CCard: CardCreator,
  CCardHeader: CustomHeader,
  CCardBody: CustomCardBody,
  CCardFooter: CustomCardFooter,
}

export const renderComponent = (config) => {
  console.log(config)
  if (typeof keysToComponentMap[config.component] !== 'undefined') {
    return createElement(
      keysToComponentMap[config.component],
      config.children &&
        (typeof config.children === 'string'
          ? config.children
          : config.children.map((c) => renderComponent(c))),
    )
  }
}

And here's the dummy data I've used to test

export const config = {
  component: 'CCard',
  children: [
    {
      component: 'CCardHeader',
      children: ['dummy'],
    },
    {
      component: 'CCardBody',
      children: ['dummy'],
    },
    {
      component: 'CCardFooter',
      children: ['dummy'],
    },
  ],
}

export default config

In theory this should recursively create elements and render them in DOM but for some reason I can't get this to work.

1 Answers

Apparently I was getting the children array wrong with my dummy data if it is going to be a simple string then I should have used children:"dummy" instead. Bit of a dumb mistake and took way too long to solve.

Related