In a react project, the end user can generate CSS using a tool.
I found how to generate JS object and pass it to style={} attribute but I want to convert the generated JS object to CSS string, so I can save it and use it in other places.
I want to convert JSObject to CSS:
JSObject [Sample - Input]
JSObject: {
lineHeight: 1,
fontSize: 15,
padding: 0,
margin: 0,
msBoxShadow: '0 0 1px 1px #000',
MozBoxShadow: '0 0 1px 1px #000',
OBoxShadow: '0 0 1px 1px #000',
WebkitBoxShadow: '0 0 1px 1px #000',
boxShadow: '0 0 1px 1px #000'
}
Expected CSS [Sample - Output]
.cssClass{
line-height: 1;
font-size: 15px;
padding: 0px;
margin: 0px;
box-shadow: rgb(0, 0, 0) 0px 0px 1px 1px;
}
I found a solution for my question and posting here for future searcher.
I made this simple function to convert JS object to CSS string:
export const JSToCSS = (JS) => {
let cssString = "";
for (let objectKey in JS) {
cssString += objectKey.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`) + ": " + JS[objectKey] + ";\n";
}
return cssString;
};
While the accepted answer is a great and simple solution to the problem, for completeness I would also want to suggest the css NPM package and its stringify method that adds features that someone visiting this question may be interested in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With