Dynamic Component Generation in React! Creating A Page with JSON!

...
if(type === "text")
return <Textfield/>
if(type === "select")
return <Select/>
if(type === "Text">
return <Text/>
...
React.createElement(YourComponent, {...propsForYourComponent});
const elements = {
Textfield,
Text
...
}
...
return (
<>
{React.createElement(elements.Textfield, {...props})}
{React.createElement(elements.Text, {...props})}
...
</>
)
React.createElement(elements["Textfield"], {...props});
const Element = ({type, props}) => {
return React.createElement(elements["Textfield"], props);
}

What does that mean?

This means you can create your simple pages with a single JSON!

const page = [
{
type: "Header",
},
{
type: "Textfield",
props: {
label: "Simple Textfield",
placeholder: "Simple placeholder",
}
},
{
type: "Selectfield",
props: {
label: "Simple Selectfield",
options: [
{
value: "opt1",
label: "Option1",
}
]
}
}
]
  • A simple UI component sets,
  • An array that has the page structure,
  • Element component which creates the components dynamically,
  • Page component which creates the pages dynamically

Why should I do that?

  1. It helps you keep your components cleaner. So, you don't lose yourself in the component.
  2. You can control all of your page structure in one place. So, you can change the layout easily.
  3. If you use a third-party UI library, you can easily change it. All you need to is change the imports and adapt the components to the new UI library.
  4. You can implement JSON Schema Forms easily! You can even create pages from a Database.
  5. It helps in keeping the look of your pages similar.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store