Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically creating React components using recursion

I’m trying to create react components dynamically based on my JSON structure using a recursive function. Here is my implementation.

Edit Dynamic Components from JSON with React (forked)

components.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

Edit Dynamic Components from JSON with React (forked)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading