1
 <Grid item>
          {attributesState.attributesData.socialPlatform.map((platform) => {
            <SocialButton
              isSelected={socialPlatform === platform.name}
              icon={<`${platform.name}Logo` />}
              onClick={() => {
                setSocialPlatform(SocialPlatform.BEHANCE);
              }}
            />;
          })}

I'm getting this error:

Type 'boolean' is not assignable to type 'ReactElement<any, string | JSXElementConstructor>'.ts(2322) component.tsx(7, 3): The expected type comes from property 'icon' which is declared here on type 'IntrinsicAttributes & SocialButtonProps' (JSX attribute) icon: React.ReactElement<any, string | React.JSXElementConstructor>

Marinescu
  • 429
  • 3
  • 18
  • Does this answer your question? [React / JSX Dynamic Component Name](https://stackoverflow.com/questions/29875869/react-jsx-dynamic-component-name) – Asad Jivani Aug 16 '21 at 08:27

1 Answers1

0

You should create a map/object to lookup the component you want actually rendered. In the mapping callback use the string template as a computed key into the lookup map/object, access the component value, and render.

Choosing the type at runtime

// ... import icon components

const icons = {
  icon1: Icon1Component,
  icon2: Icon2Component,
  .... etc...
};

...

{attributesState.attributesData.socialPlatform.map((platform) => {
  const IconComponent = icons[`${platform.name}Logo`];
  return (
    <SocialButton
      isSelected={socialPlatform === platform.name}
      icon={<IconComponent />}
      onClick={() => {
        setSocialPlatform(SocialPlatform.BEHANCE);
      }}
    />
  );
})}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • I have the logo: import { ReactComponent as FacebookLogo } from '~/assets/img/icons/Facebook.svg'; The icons object: const icons = { Facebook: FacebookLogo, }; And the component: const IconComponent = icons[`${platform.name}`]; return ( } onClick={() => { setSocialPlatform(platform.name); }} /> ); – Marinescu Aug 16 '21 at 09:13
  • And it gets the error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ Facebook: FunctionComponent & { title?: string | undefined; }>; }'. No index signature with a parameter of type 'string' was found on type '{ Facebook: FunctionComponent & { title?: string | undefined; }>; }' – Marinescu Aug 16 '21 at 09:14
  • @Marinescu Are you certain what is supposed to be passed via this `icon` prop? It sort of seems like `SocialButton` is expecting a reference to a React components, not a JSX literal of it. Can you add what `SocialButton` is to your question? – Drew Reese Aug 16 '21 at 15:20