How to use an SVG file in a SvgIcon in Material-UI

Mehran picture Mehran · Jul 21, 2016 · Viewed 35.8k times · Source

I've got an SVG file and I want to make an SvgIcon component out of it, how should I do that?

In the documentation, all the examples use either predefined Material Icons or a strange notation of <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" /> which I have no idea what it is!

Answer

Christos Lytras picture Christos Lytras · Jun 2, 2019

To use a SVG file as an icon, I used the <Icon/> component with an <img/> element inside, setting the height: 100% to the img element and textAlign: center to the root class of the <Icon/> component did the trick:

JSX:

import Icon from '@material-ui/core/Icon';
import { makeStyles } from '@material-ui/styles';
...

<Icon classes={{root: classes.iconRoot}}>
  <img className={classes.imageIcon} src="/graphics/firebase-logo.svg"/>
</Icon>

Styles:

const useStyles = makeStyles({
  imageIcon: {
    height: '100%'
  },
  iconRoot: {
    textAlign: 'center'
  }
});

Result:

Material UI Drawer Icon from SVG

UPDATE

As Lorenz Haase mentions in the comments, there is a slighly cuttting of the SVG at the bottom, which it can be fixed if we use flexbox and inherit width and height:

const useStyles = makeStyles({
  imageIcon: {
    display: 'flex',
    height: 'inherit',
    width: 'inherit'
  }
});