Last active
August 29, 2015 14:24
-
-
Save ryanmcgrath/81ce6857f20fac53f712 to your computer and use it in GitHub Desktop.
An incredibly basic module that handles injecting SVG sprites into the document, and then displaying it in a simple <SVG> component tag. Allows for easy PNG fallback for older/unsupported browsers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import SVG from './SVG'; | |
class MyComponent extends React.Component { | |
render() { | |
return <SVG uri="my-icon-ref" width={44} height={44} /> | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import icons from './icons'; | |
// This will inject our packaged SVG into the document, if it belongs there | |
const supportsSVGNatively = ( | |
!!document.createElementNS && | |
!!document.createElementNS('http://www.w3.org/2000/svg', "svg").createSVGRect | |
); | |
if(supportsSVGNatively) { | |
let parser = new DOMParser(), | |
svgDoc = parser.parseFromString(icons, 'text/xml'); | |
document.body.insertBefore(svgDoc.firstChild, document.body.firstChild); | |
} | |
export default class SVG extends React.Component { | |
static defaultProps = { | |
x: 0, | |
y: 0, | |
w: 32, | |
h: 32, | |
width: 0, | |
height: 0, | |
uri: '' | |
} | |
static propTypes = { | |
x: React.PropTypes.number, | |
y: React.PropTypes.number, | |
w: React.PropTypes.number, | |
h: React.PropTypes.number, | |
width: React.PropTypes.number.isRequired, | |
height: React.PropTypes.number, | |
uri: React.PropTypes.string.isRequired | |
} | |
render() { | |
if(!supportsSVGNatively) // @TODO: Polyfill PNGs or something, just span for now | |
return <span/>; | |
let p = this.props, | |
uri = `<use xlink:href="#${p.uri}"></use>`, | |
viewbox = `${p.x} ${p.y} ${p.w} ${p.h}`; | |
return <svg width={p.width} height={p.height} viewBox={viewbox} dangerouslySetInnerHTML={{__html: uri}}/>; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment