Created
June 17, 2024 06:22
-
-
Save NarekChang/2e0dc9a22f22d5fdd83dca315b2bc48b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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