Skip to content

Instantly share code, notes, and snippets.

@sher
Created June 27, 2015 04:06
Show Gist options
  • Save sher/23ed544e29804ad24a11 to your computer and use it in GitHub Desktop.
Save sher/23ed544e29804ad24a11 to your computer and use it in GitHub Desktop.
Styled React component mixin with reference counting
function _mount(style, styles) {
for (var i = 0; i < styles.length; i++) {
if (style == styles[i].getAttribute('href')) {
styles[i].dataset.refc++;
return;
}
}
var newStyle = document.createElement('link');
newStyle.setAttribute('rel', 'stylesheet');
newStyle.setAttribute('type', 'text/css');
newStyle.setAttribute('href', style);
newStyle.dataset.refc = 1;
document.head.appendChild(newStyle);
}
function _unmount(style, styles) {
var existingStyle;
for (var i = 0; i < styles.length; i++) {
if (style == styles[i].getAttribute('href')) {
styles[i].dataset.refc--;
existingStyle = styles[i];
break;
}
}
if (existingStyle.dataset.refc <= 0) {
document.head.removeChild(existingStyle);
}
}
var StyleMixin = {
componentWillMount() {
if (this.style) {
var links = document.head.getElementsByTagName('link');
var styles = [];
for (var i = 0; i < links.length; i++) {
if (links[i].getAttribute('rel') == 'stylesheet') {
styles.push(links[i]);
}
}
if (this.style.constructor === Array) {
this.style.forEach(function (style) {
_mount(style, styles);
})
}
else {
_mount(this.style, styles);
}
}
},
componentWillUnmount() {
if (this.style) {
var links = document.head.getElementsByTagName('link');
var styles = [];
for (var i = 0; i < links.length; i++) {
if (links[i].getAttribute('rel') == 'stylesheet') {
styles.push(links[i]);
}
}
if (this.style.constructor === Array) {
this.style.forEach(function (style) {
_unmount(style, styles);
})
}
else {
_unmount(this.style, styles);
}
}
}
}
export default StyleMixin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment