3
votes

I need to pass custom css properties inline to a React component (Google Model Viewer in this instance),combined with more run-of-the-mill styles (background width,height etc). There's quite a lot of questions on using custom properties inline with react, but I couldn't see one for specifically combing the properties with other styles.

I have the styles here, with the commented out style being an example of the custom property.

const styles = {
      width: "100%",
      height: "100%",
      background: this.props.background,
     // "--progress-bar-height": this.props.progressBarHeight
 };

The const gets passed into rendering the component:

return (
      <model-viewer
        style={styles}
      </model-viewer>

How do I combine the usual inline styles with the custom properties to add inline?

I tried adding it as a variable (as seen elsewhere on SO):

const progressBarHeight={ "--progress-bar-height": this.props.progressBarHeight };

But wasn't sure how to combine that with the {styles} . I tried longhand declaring each style and adding the variable to the list, but that didnt work either:

 style={{ background: styles.background, width: styles.width, height: styles.height, progressBarHeight }}

Any tips?

2

2 Answers

3
votes

You can simply use object spreading for this

style={{...styles, ...progressBarHeight }} // progressBarHeight = { "--customrvar" : '1px'}

Here's a working demo

0
votes

Shouldn't a simple object map work? Here is a sample code -

const styles = {
      width: "100%",
      height: "100%",
      background: "this.props.background",
      //"--progress-bar-height": "black"
 };
 
 const props = {
      "--progress-bar-height": "white"
 }
 
 for(let i in props)
 {
    styles[i] = props[i];   
 }
 
 for(let i in styles)
 {
    console.log(styles[i]);   
 }

Also fiddle link https://jsfiddle.net/bacnh8gx/ And then the resulting combined style goes into props of your component.