I am working with React, and I need to be able to take an css object literal and convert it to a string. React automatically does this for style objects added to the style tag. Is there a function in React, or another library, that you can use to convert object literals to css strings?
For Example, I need to take a literal that looks like:
{
fontSize: '4em',
zIndex: 2,
marginLeft: '-.5em'
}
And convert it to a css string:
"font-size: 4em; z-index: 2, margin-left: -.5em"
What is the best tool to use for this job?
here's a dead-simple ES5 conversion routine for browsers:
function o2s(o){
var elm=new Option;
Object.keys(o).forEach(function(a){elm.style[a]=o[a];});
return elm.getAttribute("style");
}
// test/usage:
o2s({
fontSize: '4em',
zIndex: 2,
marginLeft: '-.5em'
});
// == "font-size: 4em; z-index: 2; margin-left: -0.5em;"
this approach also self-validates the CSS rules and works with any known vendor prefixes and non-standard properties.
I believe this is what you're looking for: https://www.npmjs.com/package/apeman-react-style
You can choose whether or not to return it as a string literal or style object data.
Hope that helps!
You can make it with react-style-object-to-css
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.