1

I have an object of all apps:

 export const allApps: appInterface[] = [
  {
    id: uuidv4(),
    name: "Minesweeper",
    icon: minesweeperIcon,
    disabled: false,
  },
];

I want to add component property to each object like this:

 export const allApps: appInterface[] = [
  {
    id: uuidv4(),
    name: "Minesweeper",
    icon: minesweeperIcon,
    disabled: false,
    component: Minesweeper, //It is imported as import Minesweeper from ../Components/Minesweeper";
  },
];

And then I want to display all components in App.js:

allApps.forEach((app)=>{
  <div>{app.component}<div> // for eg: <div><Minesweeper/></div>
});

Is this possible to do?

Syed Mazhar
  • 119
  • 2
  • 10
  • 3
    Yes, it's possible. – Mina Aug 20 '22 at 10:00
  • Indeed. Components are just functions. You can assign them however you like. Writing JSX is just another syntax for invoking these functions and concatenating their output. – Marcus Ilgner Aug 20 '22 at 10:03
  • 1
    Does this answer your question? [React / JSX Dynamic Component Name](https://stackoverflow.com/questions/29875869/react-jsx-dynamic-component-name) – Sergiu Paraschiv Aug 20 '22 at 10:03
  • 1
    Does this answer your question? [React: storing components in an object](https://stackoverflow.com/questions/36073258/react-storing-components-in-an-object) – Harsh Gupta Aug 20 '22 at 10:03

1 Answers1

3

Try as below code it should work.

allApps.map((app)=>{
const { component: Component } = app;
  return <Component />;
});
  • For those wanting more details, it seems like you should never call a component function directly and instead use JSX/TSX semantics as shown in this answer. In my case it led to a pretty tricky bug, where it worked for some components and not for others. I struggled so much to find the right semantics for going from function to component in this case, thanks a lot for this elegant solution ! – Felix Bertoni Aug 05 '23 at 21:36