Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-JS convert CSS-in-JS to CSS string

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;
}
like image 328
Mohammed Tawfik Avatar asked Jul 26 '26 18:07

Mohammed Tawfik


2 Answers

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;
};
like image 198
Mohammed Tawfik Avatar answered Jul 29 '26 07:07

Mohammed Tawfik


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.

like image 42
Valery Avatar answered Jul 29 '26 08:07

Valery



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!