Home > Software engineering >  Dynamically creating React components using recursion
Dynamically creating React components using recursion

Time:09-04

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

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:

There is a third argument in the Edit Dynamic Components from JSON with React (forked)

  • Related