DEV Community

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

Collapse
 
seanmclem profile image
Seanmclem

I wish React had something like Dynamic Components. Looks like I'll have to dust off my Vue experience and build something fun like this. Just in time for Vue 3 😊

Collapse
 
yaketymatt profile image
Matt Anderson

I think it does Sean, try searching "dynamic component React" and you'll see a few tutorials. I haven't worked with React myself I must admit, so perhaps they have different meaning attached to "dynamic component". When I get chance I'll look into it myself and update the article.

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.