7

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;
}
2
  • check this github.com/aramk/CSSJSON Commented Dec 14, 2017 at 16:46
  • 1
    @monssef Thanks but I want to convert Javascript object that generated using CSS-in-JS or JSS libraries to normal css [not JSON] Commented Dec 14, 2017 at 16:52

2 Answers 2

9

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;
};
Sign up to request clarification or add additional context in comments.

3 Comments

what about the prefixes ?
@monssef when using the simple function I made it will convert this MozBoxShadow to the css prefix -moz-box-shadow and this works perfectly on my project, thanks :)
I have made a codepen based on this codepen.io/BerkeKaragoz/pen/xxWRYdY
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.