Home > OS >  How to render HTML elements based on a nested object in React?
How to render HTML elements based on a nested object in React?

Time:01-27

I have an object similar to this:

const demoData2 = {
    data: [
      {
        fieldType: "DIVISION",
        data: [{ fieldType: "BUTTON" }, { fieldType: "TEXT" }],
      },
      { fieldType: "BUTTON" },
      { fieldType: "TEXT" },
    ],
  }

Have to write a function which takes this object as input and it should return HTML(JSX) elements in the same format. Note: This is just an example object. So please help me with the more generic function but the data format will be the same.

I have tried to make use of recursive functions but of no use

Expected output: Expected similar to this

CodePudding user response:

const components = {
   DIVISION: Division,   // this is component
   BUTTON: 'button',     // this is string
   TEXT: 'p'
}

const generateDom = (data, key) => {
if (!data) return null
const Wrapper = components[data.fieldType]
const content = Array.isArray(data.data) ? data.data.map(generateDom) : generateDom(data.data)
if (Wrapper){
   return <Wrapper key={key}>{content}</Wrapper>
}
return content
}

const DOM = <>{generateDom(demoData2)}</>

Something like this should work for you

Your data can contain string as well, not only array

CodePudding user response:

You should use React.createElement to dynamically generate JSX-components. Also: all your data seems all Uppercase here while React uses PascalCase for component tag-names.

It might look something like this:

//Example Data

const demoData2 = { 
  data: [
    {
      fieldType: "BUTTON",
      tagName: 'MyButtonComponent'
    },
    {
      fieldType: "OTHERCOMPONENT",
      tagName: 'MyOtherComponent'
    },
  ],
}

//Then something like this

const arrayOfElements = demoData2.data.map((elementData, index) => { 
  return React.createElement(elementData.tagName, {
    data: elementData.fieldType,
    key: elementData.fieldType '-' index
  });
})

The const arrayOfElements can now be used in your render-function.

  • Related