I'm trying to create react components dynamically based on my JSON structure using a recursive function. Here is my implementation.
components.js
import React from "react";
import Text from "./components/Text";
import Image from "./components/Image";
const Components = {
text: Text,
image: Image
};
export default (block) => {
if (typeof Components[block.type] !== "undefined") {
return React.createElement(Components[block.type], {
key: block.id,
block: block
});
}
return React.createElement(
() => <div>The component {block.type} has not been created yet.</div>,
{ key: block.id }
);
};
dummy data
const data = {
userId: 123123,
pages: [
{
id: 1,
type: "div",
data: { text: "hello" },
content: [
{
id: 123,
type: "text",
data: { text: "hello" }
},
{
id: 456,
type: "image",
data: { source: "url", link: "url" }
}
]
}
]
};
CodePudding user response: