Search code examples
javascriptcssreactjsinline-styles

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


I wanted to set my element's style as such:

this.refs.element.style = {
    ...this.props.style,
    background: 'blue',
};

But apparently you can't use an object to set the ref's style. I have to use a CSS style string with ; separating the prop:values

I'm aware that most people would set style in the render function, but for performance reasons, I can't repeatedly re-render.


Solution

  • 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()}`);