Skip to content

Instantly share code, notes, and snippets.

@kshirish
Created June 9, 2023 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kshirish/f9b172ace879091477f5e0321e06fdae to your computer and use it in GitHub Desktop.
Save kshirish/f9b172ace879091477f5e0321e06fdae to your computer and use it in GitHub Desktop.
Dynamic render through JSON schema
import * as React from "react";
const Text = (props) => {
return (
<div style={{ border: "1px solid red", padding: "20px" }}>
<p>this is text</p>
<div>{props.children}</div>
</div>
);
};
const Space = (props) => {
return (
<div style={{ border: "1px solid green", padding: "20px" }}>
<p>this is space</p>
{props.lol ? <div>this is the end</div> : <div>{props.children}</div>}
</div>
);
};
const Layout = (props) => {
return (
<div style={{ border: "1px solid blue", padding: "20px" }}>
<p>this is layout</p>
<div>{props.children}</div>
</div>
);
};
function renderComponent(component) {
if (typeof component !== "object") {
return component;
}
const Tagname = component.type;
if (component.children.length) {
return (
<Tagname key={component.id} {...component.props}>
{component.children.map(renderComponent)}
</Tagname>
);
}
return <Tagname key={component.id} {...component.props} />;
}
function renderPage(schema) {
return schema.map(renderComponent);
}
const App = () => {
const schema = [
{
id: 1,
type: Layout,
props: {
name: "john doe",
age: 23,
},
children: [
{
id: 11,
type: Space,
props: {},
children: ["Sample text 1"],
},
{
id: 12,
type: Space,
props: {
lol: true,
},
children: ["Sample text 2"],
},
{
id: 13,
type: Space,
props: {},
children: [
{
id: 14,
type: Text,
props: {},
children: [
{
id: 15,
type: "h3",
props: {},
children: ["Sample text 3"],
},
],
},
],
},
],
},
{
id: 2,
type: "input",
props: {
type: "text",
placeholder: "Enter your name",
},
children: [],
},
];
return renderPage(schema);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment