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

后端 未结 2 1510
终归单人心
终归单人心 2021-02-11 13:09

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 Icon

2条回答
  •  余生分开走
    2021-02-11 14:10

    1. Using component and an element

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

    JSX:

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

    Styles:

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

    Result:

    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'
      }
    });
    

    2. Using component and @svgr/webpack webpack loader

    According to the official MUI documentation, we can use component props and have a @svgr/webpack loader to load .svg files using ESM imports.

    Component prop

    You can use the SvgIcon wrapper even if your icons are saved in the .svg format. svgr has loaders to import SVG files and use them as React components. For example, with webpack:

    // webpack.config.js
    {
      test: /\.svg$/,
      use: ['@svgr/webpack'],
    }
    
    // ---
    import StarIcon from './star.svg';
    
    
    

    It's also possible to use it with "url-loader" or "file-loader". It's the approach used by Create React App.

    // webpack.config.js
    {
      test: /\.svg$/,
      use: ['@svgr/webpack', 'url-loader'],
    }
    
    // ---
    import { ReactComponent as StarIcon } from './star.svg';
    
    
    

提交回复
热议问题