How do I load SVGs directly in my React component using webpack?

天涯浪子 提交于 2019-12-01 16:37:07

Since your SVG content is stored as a string and not as a React element, you'll need to use Dangerously Set innerHTML.

var NextIcon = require('material-design-icons/navigation/svg/production/ic_chevron_right_18px.svg');

var NextButton = React.createClass({
  render: function() {
    return (
      <Link to={this.props.target} className='button--next'>
        {this.props.label} <span dangerouslySetInnerHTML={{ __html: NextIcon }} />
      </Link>
    )
  }
});

You could perhaps work your way around this by creating a webpack loader that automatically does this for you whenever you require a SVG file.

dangerouslySetInnerHTML.loader.js

module.exports = function(content) {
    return (
        'module.exports = require("react").createElement("span", {' +
            'dangerouslySetInnerHTML: {' +
                '__html: ' + JSON.stringify(content) +
            '}' +
        '});'
    );
};

webpack.config.js

loaders: [
  {
    test: /\.svg$/,
    loader: require.resolve('./dangerouslySetInnerHTML.loader'),
    exclude: /node_modules/,
  },
],

The previous code snippet would then become:

var NextIcon = require('material-design-icons/navigation/svg/production/ic_chevron_right_18px.svg');

var NextButton = React.createClass({
  render: function() {
    return (
      <Link to={this.props.target} className='button--next'>
        {this.props.label} {NextIcon}
      </Link>
    )
  }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!