Skip to content

Instantly share code, notes, and snippets.

@lourd
Created August 13, 2015 06:30
Show Gist options
  • Save lourd/b46104d81be593032cd1 to your computer and use it in GitHub Desktop.
Save lourd/b46104d81be593032cd1 to your computer and use it in GitHub Desktop.
An awesome FontAwesome React component
import React from 'react';
import radium from 'radium';
const version = '4.4.0';
const url = 'https://maxcdn.bootstrapcdn.com/font-awesome';
const fontFace = `
@font-face {
font-family: 'FontAwesome';
src: url('${url}/${version}/fonts/fontawesome-webfont.eot?v=${version}');
src: url('${url}/${version}/fonts/fontawesome-webfont.eot?#iefix&v=${version}') format('embedded-opentype'),
url('${url}/${version}/fonts/fontawesome-webfont.woff2?v=${version}') format('woff2'),
url('${url}/${version}/fonts/fontawesome-webfont.woff?v=${version}') format('woff'),
url('${url}/${version}/fonts/fontawesome-webfont.ttf?v=${version}') format('truetype'),
url('${url}/${version}/fonts/fontawesome-webfont.svg?v=${version}#fontawesomeregular') format('svg');
font-weight: normal;
font-style: normal;
}
`;
const faStyle = {
display: 'inline-block',
fontFamily: 'FontAwesome',
fontSize: 'inherit',
fontVariant: 'normal',
fontWeight: 'normal',
lineHeight: 1,
textRendering: 'auto',
WebkitFontSmoothing: 'antialiased',
MozOsxFontSmoothing: 'grayscale',
};
// TODO add more codes!
const hexCodes = {
youtube: '\uf167',
twitter: '\uf099',
instagram: '\uf16d',
github: '\uf09b',
facebook: '\uf09a',
'play-circle-o': '\uf01d',
};
let fontLoaded = false;
function writeFontFace() {
const styleEl = document.createElement('style');
styleEl.setAttribute('type', 'text/css');
styleEl.innerHTML = fontFace;
document.head.appendChild(styleEl);
}
const FontAwesome = React.createClass({
propTypes: {
name: React.PropTypes.oneOf(Object.keys(hexCodes)).isRequired,
style: React.PropTypes.object,
},
componentWillMount() {
if ( !fontLoaded ) {
writeFontFace();
fontLoaded = true;
}
},
render() {
const { name, style } = this.props;
const hexCode = hexCodes[name];
return <span style={[faStyle, style]}>{hexCode}</span>;
},
});
export default radium(FontAwesome);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment