0

so i want to create a a dynamic react component that the name come from the backend like:

[
  {
    "data": {
      "header": "this is header one",
      "article": "this is article one"
    },
    "componentname": "Articleone"
  },
  {
    "data": {
      "header": "this is header two",
      "article": "this is article two"
    },
    "componentname": "Articletwo"
  }
]

so i want to create the component based on the data from the backend, as you see in the componentname.

so i made a research of it and the result i found is this:

  const ComponentName = (data) => {
    const Component = data[0].componentname;
    const data = data[0].data;
    return <Component data={data} />;
  };

i tried this, buts its gave an error:

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

i tried many other methods but noting works for me.

how can i create a react dynamic component.

kxown
  • 95
  • 1
  • 6

1 Answers1

0

Try creating an enum with the componentnames as the properties for the components you want to use:

import { ComponentA, ComponentB, ComponentC } from '../components';

export const COMPONENTS_ENUM = {
  Articleone: ComponentA,
  Articletwo: ComponentB,
  Articlethree: ComponentC,
};

Then in the component you want to use those components dynamically you can do:

import { COMPONENTS_ENUM } from '../constants';

const ComponentName = (data) => {
  const componentName = data[0].componentname;
  const data = data[0].data;

  const Component = COMPONENTS_ENUM[componentName];

  return <Component data={data} />;
};

Avi
  • 1,049
  • 1
  • 5
  • 16