Skip to content
Advertisement

Combining CSS and custom CSS properties inline on a react component

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?

Advertisement

Answer

You can simply use object spreading for this

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

Here’s a working demo

Advertisement