Home > database >  What type to use for Material Ui Icons when passed as props
What type to use for Material Ui Icons when passed as props

Time:01-25

What type do I need when I want to pass Material UI Icons as props to a component

import {OverridableComponent} from "@mui/material/OverridableComponent";
import {SvgIconTypeMap} from "@mui/material";

interface IconButtonProps {
    children: OverridableComponent<SvgIconTypeMap<{}, "svg">> & {muiName: string};
    disabled?: boolean;
}

const IconButton = ({
                        children,
                        disabled = false,
                    }: IconButtonProps) => {
    return (
        <Button
            disabled={disabled}>
            {children}
        </Button>
    )
}

When I use it like this

import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';

<IconButton><AddCircleOutlineIcon/></IconButton>

I get

Type 'Element' is not assignable to type 'OverridableComponent<SvgIconTypeMap<{}, "svg">>'.   Type 'Element' provides no match for the signature '<C extends ElementType>(props: { component: C; } & { children?: ReactNode; classes?: Partial | undefined; color?: "disabled" | ... 8 more ... | undefined; ... 6 more ...; viewBox?: string | undefined; } & CommonProps & DistributiveOmit<...>): Element | null'.

I also tried

import {SvgIconComponent} from "@mui/icons-material";
children: SvgIconComponent;

giving me the same message.

CodePudding user response:

There is a difference of type between AddCircleOutlineIcon and <AddCircleOutlineIcon />

  • AddCircleOutlineIcon is of type OverridableComponent<SvgIconTypeMap<{}, "svg">> & {muiName: string};
  • <AddCircleOutlineIcon /> is of type JSX.Element

As mentioned in a comment, the easiest way to solve this is to use the IconButton Material UI component.

If you want to keep your custom component, replace the children type in your IconButtonProps interface by JSX.Element

  • Related