How to convert a JSON style object to a CSS string? How to convert a JSON style object to a CSS string? reactjs reactjs

How to convert a JSON style object to a CSS string?


A performant answer is to map and join the Object.entries with semicolons:

const style = {  ...this.props.style,  background: 'blue',};const styleString = (  Object.entries(style).map(([k, v]) => `${k}:${v}`).join(';'));

It unwraps background:'blue', to background:blue; which works well for CSS


To replace any capital letter with dash lowercase letter

k = k.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`);


this solution works in IE and handles camelCase keys like backgroundColor

const style = {    width: '1px',    height: '1px',    backgroundColor: 'red',    transform: 'rotateZ(45deg)',}const styleToString = (style) => {    return Object.keys(style).reduce((acc, key) => (        acc + key.split(/(?=[A-Z])/).join('-').toLowerCase() + ':' + style[key] + ';'    ), '');};console.log(styleToString(style));// output - "width:1px;height:1px;background-color:red;transform:rotateZ(45deg);"