DEV Community

Cover image for Extend SvgIcon sizes in React Material UI
Karl Adler
Karl Adler

Posted on

Extend SvgIcon sizes in React Material UI

Using React Material UI you have the opportunity to use any SVG file like an icon. To do so, you just wrap it into the SvgIcon component.

An example for your HomeIcon component might look like this:

import React from 'react';
import { SvgIcon, SvgIconProps } from '@mui/material';
import { ReactComponent as HomeSvg } from '../../assets/Icons/Home.svg';

function HomeIcon(props: SvgIconProps) {
  return (
    <SvgIcon component={HomeSvg} viewBox="0 0 24 24" {...props} />
  );
}

export default HomeIcon;
Enter fullscreen mode Exit fullscreen mode

Importing svg files as react components required svgr, otherwise you would need to use the SVG code as children of SvgIcon

With SvgIcon you have the possibility to set the fontSize attribute to "small", "inherit", "large" or "medium", but what if we if we would need more of this?

<HomeIcon fontSize="small" />
<HomeIcon />
<HomeIcon fontSize="large" />
<HomeIcon sx={{ fontSize: 40 }} />
Enter fullscreen mode Exit fullscreen mode

Here is where component variants come into play.

In our theme we just add a new variant to the MuiSvgIcon component. E.g. we we want an new size called huge we do it like this:

components: {
   MuiSvgIcon: {
      variants: [
        {
          props: { fontSize: 'huge' },
          style: {
            fontSize: '5rem',
          },
        },
      ],
    },
}
Enter fullscreen mode Exit fullscreen mode

That should already work, but when we are using typescript and setting it, the compiler will complain.

<HomeIcon fontSize="huge" />
Enter fullscreen mode Exit fullscreen mode

So we need to extend the interface for the component too:

declare module '@mui/material/SvgIcon' {
  interface SvgIconPropsSizeOverrides {
    huge: true;
  }
}
Enter fullscreen mode Exit fullscreen mode

Just add the above module declaration e.g. to your theme.ts and that's it.

Discussion (0)