Home > Enterprise >  How to define a SVG component with typescript in react?
How to define a SVG component with typescript in react?

Time:10-29

I am passing a SVG icons props to my component which is an array contain my SVG component data but it show me this error in typescript, I am working with material UI

Type '{ key: number; data: { id: number; icon: ReactNode; }; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; classes?: Partial<SvgIconClasses> | undefined; color?: "inherit" | "disabled" | ... 7 more ... | undefined; ... 5 more ...; viewBox?: string | undefined; } & CommonProps & Omit<...> & { ...; }'.
  Property 'data' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; classes?: Partial<SvgIconClasses> | undefined; color?: "inherit" | "disabled" | ... 7 more ... | undefined; ... 5 more ...; viewBox?: string | undefined; } & CommonProps & Omit<...> & { ...; }

This is my interface Props

interface Props {
    icons?: [
        {
            id:number;
            icon:React.ReactNode;
            style?:object;
        }
    ];

}

My SVG object

[
    {
    id:1,
    icons: MySVGIcon,
    style: iconStyle
    }
]

This is my component where I want to display svg icons

const Title: React.FC<Props> = ({icons=[]}}) => {
    return (
        <Grid container direction='row' justifyContent="center" alignItems="center">
            <Grid item xs={2}>
                {icons.map(({icon,id}) => <SVGIcon key={id} data={icon} />)}
            </Grid>

        </Grid>
    )
}

This is my SVGIcon component

import React from 'react'
import SvgIcon, { SvgIconProps } from '@mui/material/SvgIcon';


const SVGIcon:React.FC<SvgIconProps> = (props) => {
    return (
        <SvgIcon {...props} />
    )
}

CodePudding user response:

Your custom SVGIcon component has a custom prop name called icon, you need to create a custom prop type for that too:

type SVGIconProps = {
  icon: React.ReactNode;
} & SvgIconProps;

const SVGIcon: React.FC<SVGIconProps> = (props) => {
  return <SvgIcon {...props} />;
};

interface Props {
  icons?: {
    id: number;
    icon: React.ReactNode;
    style?: object;
  }[];
}

const Title: React.FC<Props> = ({ icons }) => {
  return (
    <Grid container direction="row" justifyContent="center" alignItems="center">
      <Grid item xs={2}>
        {icons.map((icon, id) => (
          <SVGIcon key={id} icon={icon} />
        ))}
      </Grid>
    </Grid>
  );
};

Codesandbox Demo

  • Related