Skip to content

Instantly share code, notes, and snippets.

@brawlins
Last active February 2, 2016 15:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brawlins/e84c28badd0e6172d9e5 to your computer and use it in GitHub Desktop.
Save brawlins/e84c28badd0e6172d9e5 to your computer and use it in GitHub Desktop.
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