Skip to content

Instantly share code, notes, and snippets.

@albinotonnina
Created August 30, 2017 20:43
Show Gist options
  • Save albinotonnina/d845e4e4de31331d77ed12219516c86c to your computer and use it in GitHub Desktop.
Save albinotonnina/d845e4e4de31331d77ed12219516c86c to your computer and use it in GitHub Desktop.
import React from 'react';
import PropTypes from 'prop-types';
import {Parser, ProcessNodeDefinitions} from 'html-to-react';
function Icon(props) {
const {name, size, color} = props;
//https://webpack.js.org/guides/dependency-management/#require-with-expression
const rawSvgContent = require(`../../icons/svg/${glyph}.svg`);
const processSvgAttributes = [
{
shouldProcessNode: () => true,
processNode: (node, children, index) => {
if(node.name === 'svg'){
node.attribs = Object.assign(node.attribs, {
width: size,
height: size
}
);
}else if(node.type === 'tag'){
node.attribs = Object.assign(node.attribs,
(() => color ? {fill: color} : {})()
);
}
return new ProcessNodeDefinitions(React).processDefaultNode(node, children, index);
}
}];
//https://www.npmjs.com/package/html-to-react#with-custom-processing-instructions
const icon = new Parser().parseWithInstructions(rawSvgContent, () => true, processSvgAttributes);
return <span className="icon">{icon}</span>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment