1

The current code is as follows

const financeFlags = [
  {
    name: "Billing",
    icon: <CompanyPinIcon />,
  },
  {
    name: "Supply",
    icon: <CommanderPinIcon />,
  }
]

Now i import the financeFlags to the component

import { financeFlags } from ...

Now i want to loop through the array, get the icon component and add new props to it.

I have modified the code as

{financeFlags.map((flag) => (
            <IconComponent flag={flag} classes={classes} />
        ))}

const IconComponent = ({ flag, classes }) => {
  const Component = flag.icon;
  return (
    <Component
      className={classNames(classes.icon, {
        [classes.unflagged]: true,
      })}
    />
  );
};

Currently, i am getting the error

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

If flag.icon is set as CompanyPinIcon instead of <CompanyPinIcon /> then there is no error. But i need to pass it in the array as <CompanyPinIcon /> since it is used in several places.

Any idea on how to fix this?

prajeesh
  • 2,202
  • 6
  • 34
  • 59
  • try change import to this --> `import financeFlags from ...` if you are asking why read [here](https://stackoverflow.com/questions/34130539/uncaught-error-invariant-violation-element-type-is-invalid-expected-a-string). – fixedDrill Mar 03 '22 at 05:12

2 Answers2

0

For the flag.icon, you need to make sure the components are imported into the same file that the array is initialized. Then, in personal experience, using React.cloneElement() may be what you are needing.

https://reactjs.org/docs/react-api.html#cloneelement

The error also states that the element type is expected to be a string or a class/function. To be a function, you would set the icon key a value like

icon: () => (<CompanyPinIcon />)
lua_python_java
  • 359
  • 2
  • 8
0
{financeFlags.map((flag) => (
            <IconComponent flag={flag} classes={classes} />
        ))}

const IconComponent = ({ flag, classes }) => {
  const Component = flag.icon;
  return (
    {
      React.cloneElement(
        flag.icon,
        {​className:classNames(classes.icon,    
              {
                ​[classes.unflagged]: true,
     ​         }
         )},
        [...pass all the children] 
      )
      
   }
  );
};

Hope this solves your problem . Refer this question on stackoverflow Link Refer official Docs Doc

Hritik Sharma
  • 1,756
  • 7
  • 24