Skip to content

Instantly share code, notes, and snippets.

@ckknight
Created July 14, 2016 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ckknight/ddf62b92deb01c2013be52815f5fc8d2 to your computer and use it in GitHub Desktop.
Save ckknight/ddf62b92deb01c2013be52815f5fc8d2 to your computer and use it in GitHub Desktop.
import { Component, PropTypes } from 'react';
function toCssKey(key) {
return `--${key}`;
}
export default class CssVariablesProvider extends Component {
static propTypes = {
variables: PropTypes.objectOf(PropTypes.string).isRequired,
children: PropTypes.element.isRequired,
};
componentWillMount() {
this.updateCssVariables({}, this.props.variables || {});
}
componentWillReceiveProps(props) {
this.updateCssVariables(this.props.variables || {}, props.variables || {});
}
updateCssVariables(oldVariables, newVariables) {
const oldKeys = Object.keys(oldVariables);
const newKeys = Object.keys(newVariables);
const keysToRemove = oldKeys.filter(key => !newKeys.includes(key));
keysToRemove.forEach(key => {
document.documentElement.style.removeProperty(toCssKey(key));
});
const keysToUpdate = newKeys.filter(key => oldVariables[key] !== newVariables[key]);
keysToUpdate.forEach(key => {
const cssKey = toCssKey(key);
document.documentElement.style.removeProperty(cssKey);
document.documentElement.style.setProperty(cssKey, newVariables[key]);
});
}
render() {
return this.props.children;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment