Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 647
neaumusic Avatar asked Jul 20 '17 05:07

neaumusic


People also ask

How do I convert a JSON object to a string?

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

What is JSON CSS?

JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting data. JSON is often used when data is sent from a server to a web page. JSON is "self-describing" and easy to understand.

Is CSS the same as JSON?

JSON is currently used to manipulate non-css things, such as chart colours which are drawn using canvas. Css has been used for a few additional things outside of this, such as sheet backgrounds. We aim to make it work with only JSON, so that managing CSS selectors won't be necessary.

What is difference between JSON parse and JSON Stringify?

The JSON. parse() function is used to convert a string into a JavaScript object while the JSON. stringify() function is used to convert a JavaScript object into a string.


1 Answers

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()}`);
like image 126
neaumusic Avatar answered Oct 11 '22 19:10

neaumusic