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.
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.
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.
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.
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.
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()}`);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With