DEV Community

Discussion on: Using Dynamic Components And a Pattern I Devised Myself to Create a No Code Web Interface Builder

Collapse
 
devhammed profile image
Hammed Oyedele • Edited

There is Dynamic components, taking this JSON data:

[
{
  "is": "s-input",
  "type": "text",
  "name": "Some input"
},
{
  "is": "s-button",
  "text": "Click Me"
}
]

You can write a renderer like this:

import React from 'react'

import SInput from './components/SInput'
import SButton from './components/SButton'

const customComponents = {
   's-input': SInput,
   's-button': SButton
}

export default function DynamicRenderer ({ data }) {
  return data.map(({ is, ...props }) => React.createElement(is in customComponents ? customComponents[is] : is, props))
}

JSX compiles down to React.createElement and that is what we are leveraging on.
I am destructuring each item in the data to extract "is" property and passing the rest of prop to the rendered component or HTML element.
If the "is" property is not in customComponents object it will fallback to render it as normal HTML tag.