Typing Svg Element React in an Object

Typing Svg Element React in an Object

I am having issues typing the following.

The issue is with the TeamIcon.

My object is defined as follows.

import TeamIcon from './components/icons/TeamIcon';

export const teamObject: Record<
  string,
  Record<string, string | React.ReactSVGElement>
> = {
  team: {
    icon: TeamIcon,
    color: '#B2649B',
  }
}

My TeamIcon looks like this:

export default (props: React.SVGProps<SVGSVGElement>) => (
  <svg width="18" height="14" viewBox="0 0 18 18" {...props}>
    <path
      fill="currentColor"
      fillRule="evenodd"
      d="..."
    />
  </svg>
);

Then the following error is being displayed:

JSX element type 'Icon' does not have any construct or call signatures.

const Icon = currentTeam.icon;

<Icon
  width="29px"
  height="29px"
  style={{ color: currentTeam.color }}
/>

Does anyone know how to type this correctly?

11

1 Answer

TeamIcon isn't a type here, it's the name of local variable, that has value of a React functional component.

So I think you want something like this, which is the type of a React functional component, with props of your choosing.

icon: React.FC<React.SVGProps<SVGSVGElement>>

A full example would be something like:

interface TeamObject {
  team: {
    icon: React.FC<React.SVGProps<SVGSVGElement>>,
    color: string,
  }
}

const teamObject: TeamObject = {
  team: {
    icon: TeamIcon,
    color: "#B2649B"
  }
};

Working example


You'll note that I got rid of this:

Record<
  string,
  Record<string, string | React.ReactSVGElement>
>

I'm not really sure what the goal of that was, but you clearly have two properties with very different types. You have icon which is a function that returns React.ReactNode and you have color which is a string. So you should be typing those explicitly.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.