Skip to content

Instantly share code, notes, and snippets.

@MoOx
Last active December 3, 2018 08:50
Show Gist options
  • Select an option

  • Save MoOx/1eb30eac43b2114de73a to your computer and use it in GitHub Desktop.

Select an option

Save MoOx/1eb30eac43b2114de73a to your computer and use it in GitHub Desktop.
Svg icons with React.js with webpack loader (svg: raw-loader)
/* small helper for outside react view */
module.exports = function(key, modifier) {
return "<svg class=\"IconSvg IconSvg-" + key + " IconSvg--" + modifier + "\"><use xlink:href=\"#IconSvg-" + key + "\"></use></svg>"
}
.IconSvg {
display: inline-block;
width: 1em;
height: 1em;
line-height: 1;
vertical-align: middle;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.IconSvg--half {
width: .5em;
height: .5em;
}
.IconSvg--white { fill: #fff }
.IconSvg--black { fill: #000 }
/**
* <IconSvg />
*
* Usage
* <IconSvg id="gear" />
* <IconSvg id="gear" modifier="white"/>
* <IconSvg id="gear" modifier="half" color="#f00" size="2rem" />
*
* @es6
* @jsx React.DOM
*/
/** @jsx React.DOM */
module React from "react"
export default React.createClass({
render() {
var iconClass = (this.props.className ? this.props.className + " " : "") + "IconSvg IconSvg-" + this.props.key
var style = {}
if (this.props.modifier) {
iconClass += " IconSvg--" + this.props.modifier
}
if (this.props.color) {
style.fill = this.props.color
}
if (this.props.size) {
style.fontSize = this.props.size
}
return this.transferPropsTo(
<svg
className={iconClass}
style={style}
dangerouslySetInnerHTML={{__html:
"<use xlink:href=\"#IconSvg-" + this.props.key + "\"></use>"
}}>
</svg>
)
}
})
var gulp = require("gulp")
var opts = require("./options")
var util = require("gulp-util")
var plumber = require("gulp-plumber")
var svgSymbols = require("gulp-svg-symbols")
module.exports = function() {
return gulp.src("./src/components/**/icons/*.svg")
.pipe(opts.plumber ? plumber() : util.noop())
.pipe(svgSymbols({
svgId: "IconSvg-%f",
className: ".IconSvg-%f",
fontSize: 512 // svg icons default font-size
}))
.pipe(gulp.dest("./dist/"))
}
@gaearon
Copy link

gaearon commented Jun 5, 2014

We use the same convention for modifiers in React. :-)

@wmertens
Copy link

@MoOx do you have a solution for using the same icon multiple times in the same page without having the same markup multiple times, causing more work for the browser?

@wmertens
Copy link

Ooh found a performance comparison (font files win) and apparently there's a symbol mode in svg.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment