Skip to content

Instantly share code, notes, and snippets.

@nishanbajracharya
Created November 3, 2019 09:11
Show Gist options
  • Save nishanbajracharya/06c0b958089c456f1f6129a51d339ca4 to your computer and use it in GitHub Desktop.
Save nishanbajracharya/06c0b958089c456f1f6129a51d339ca4 to your computer and use it in GitHub Desktop.
Convert JS style object to injectable CSS
function toKebabCase(string) {
return string.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase();
}
function hash(string) {
var h = 0
var i = 0;
if (string.length > 0) {
while (i < string.length) {
h = (h << 5) - h + string.charCodeAt(i++) | 0;
}
}
return h;
}
var unitless = [
'z-index',
'font-weight',
'line-height',
'counter-reset',
'counter-increment',
'volume',
'stress',
'pitch-range',
'richness',
];
function css(style) {
var output = '{';
style && Object.keys(style).forEach(function (key) {
var property = toKebabCase(key);
var value = style[key];
if (typeof value === 'number' && value > 0 && !unitless.includes(property)) {
value += 'px';
}
output += `\n\t${property}: ${value};`
});
output += `\n}`;
var className = hash(JSON.stringify(style));
return `.css-${className} ${output}`;
}
var style = {
margin: 10,
color: 'red',
padding: '20px',
fontFamily: '"Roboto", sans-serif',
};
console.log(css(style));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment