Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
React component for using SVG icons in your application.
"use strict";
var React = require('react');
/**
* SVG icon component
*
* Renders an icon with the given symbol id. Assumes you have a SVG definitions
* document with symbols defined. React sometimes chokes on SVGs defined in
* JSX, so a workaround is to wrap it in a tag and set the inner HTML of that
* tag to a string representing the SVG.
*/
var SvgIcon = React.createClass({
propTypes: {
classNames: React.PropTypes.array, // array of class names
show: React.PropTypes.bool, // conditionally render when this value is true
symbolId: React.PropTypes.string.isRequired, // symbol id from SVG definitions document
wrapperTag: React.PropTypes.string // HTML tag name to wrap SVG in
},
render: function() {
// set defaults
var classNames = this.props.classNames || [];
var show = (typeof this.props.show !== 'undefined') ? this.props.show : true;
var wrapperTag = this.props.wrapperTag || 'span';
// define SVG to use and add given classes
var svgString = '<svg class="CLASS_NAMES"><use xlink:href="#SYMBOL_ID"></use></svg>';
svgString = svgString.replace('CLASS_NAMES', classNames.join(' '));
svgString = svgString.replace('SYMBOL_ID', this.props.symbolId);
// only render if show value is true
if (show) {
return React.createElement(wrapperTag, { dangerouslySetInnerHTML: {__html: svgString} });
} else {
return null;
}
}
});
module.exports = SvgIcon;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment