Skip to content

Instantly share code, notes, and snippets.

@hoyangtsai
Last active August 21, 2022 10:17
Show Gist options
  • Save hoyangtsai/b77d6617fbbe62aee62a8941a596ab77 to your computer and use it in GitHub Desktop.
Save hoyangtsai/b77d6617fbbe62aee62a8941a596ab77 to your computer and use it in GitHub Desktop.
Simple convert an object of styles into #inlineStyle #CSS string
const style = {
width: 400,
height: 300,
position: 'fixed',
top: 900,
left: 60,
'z-index': 1234
}
const inline = Object.entries(style).reduce((prev, curr) => {
let [attr, val] = curr;
const attrWithoutUnit = ['z-index'];
if (Number.isInteger(val) && !attrWithoutUnit.includes(attr)) {
val += 'px';
}
return prev += `${attr}: ${val}; `;
}, '');
const getInlineStyles = (styles) => {
return Object.entries(styles).reduce((prev, curr) => {
// eslint-disable-next-line
let [attr, val] = curr;
const attrWithoutUnit = ['z-index'];
if (Number.isInteger(val) && !attrWithoutUnit.includes(attr)) {
val += 'px';
}
// eslint-disable-next-line
return prev += `${attr}: ${val}; `;
}, '');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment