Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save NarekChang/2e0dc9a22f22d5fdd83dca315b2bc48b to your computer and use it in GitHub Desktop.
Save NarekChang/2e0dc9a22f22d5fdd83dca315b2bc48b to your computer and use it in GitHub Desktop.
import fs from "fs";
function generateReactComponentsFromJson(jsonData) {
if (!jsonData) return null;
return Object.keys(jsonData).map((key, index) => {
const componentData = jsonData[key];
const { type, props, children } = componentData;
let childrenComponents = null;
if (children) {
childrenComponents = generateReactComponentsFromJson(children);
}
const componentProps = props ? JSON.stringify(props) : null;
return `<${type} key={${index}} {...${componentProps}}>
{childrenComponents}
</${type}>`;
});
}
const jsonData = {
div: {
type: "div",
props: {
className: "container",
},
children: {
h1: {
type: "h1",
props: {
className: "title",
},
children: "Hello, React!",
},
p: {
type: "p",
children: "This is a sample React component generator.",
},
},
},
};
const ReactComponents = generateReactComponentsFromJson(jsonData);
fs.writeFile("./testComp.tsx", ReactComponents, (err) => {
if (err) {
console.error(err);
} else {
// file written successfully
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment