Skip to content

Instantly share code, notes, and snippets.

@lushc
Last active March 28, 2018 19:39
Show Gist options
  • Save lushc/9e1699e5d41f863cd1c58d58385dbe9b to your computer and use it in GitHub Desktop.
Save lushc/9e1699e5d41f863cd1c58d58385dbe9b to your computer and use it in GitHub Desktop.
React component for Feather icons (https://github.com/feathericons/feather)
/**
* @author https://github.com/alexdunne
* @author https://github.com/lushc
*/
import React from "react";
import PropTypes from "prop-types";
import Feather from "feather-icons";
class FeatherIcon extends React.Component {
state = {
renderedChildren: false,
};
render() {
const { children, name, spin, ...attrs } = this.props;
let elements = children;
if (spin) {
elements = (
<animateTransform
attributeName="transform"
attributeType="XML"
type="rotate"
from="0 0 0"
to="360 0 0"
dur="2s"
repeatCount="indefinite"
/>
);
}
return (
<span
ref={span => {
if (span && elements && !this.state.renderedChildren) {
span.getElementsByTagName("svg")[0].innerHTML += this.childrenToString(elements);
this.setState({ renderedChildren: true });
}
}}
dangerouslySetInnerHTML={{ __html: Feather.icons[name].toSvg({...attrs}) }}
/>
);
}
// horrible hack to enable the icon SVG to contain elements such as <animateTransform />
childrenToString(children) {
return React.Children.toArray(children).reduce((acc, element) => {
let props = Object.keys(element.props).reduce(
(acc, prop) => (acc += `${prop}="${element.props[prop]}"`),
""
);
return (acc += `<${element.type} ${props} />`);
}, "");
}
}
FeatherIcon.propTypes = {
children: PropTypes.oneOfType([PropTypes.element, PropTypes.arrayOf(PropTypes.element)]),
name: PropTypes.string.isRequired,
spin: PropTypes.any,
class: PropTypes.string,
xmlns: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
viewBox: PropTypes.string,
fill: PropTypes.string,
stroke: PropTypes.string,
"stroke-width": PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
"stroke-linecap": PropTypes.string,
"stroke-linejoin": PropTypes.string,
};
export default FeatherIcon;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment