Created
July 14, 2016 23:22
-
-
Save ckknight/ddf62b92deb01c2013be52815f5fc8d2 to your computer and use it in GitHub Desktop.
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 { 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