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" }
}
]
}
]
};
>Solution :
There is a third argument in the React.createElement which is to render the children. Extended your Components component like below to do the recursive rendering:
const ComponentsMap = {
div: Div,
text: Text,
image: Image
};
const Components = (block) => {
if (typeof ComponentsMap[block.type] !== "undefined") {
return React.createElement(
ComponentsMap[block.type],
{
key: block.id,
block: block
},
block.content ? block.content.map((subComp) => Components(subComp)) : null
);
}
return React.createElement(
() => <div>The component {block.type} has not been created yet.</div>,
{ key: block.id }
);
};
export default Components;
Working Demo: