3

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 Answers 2

4

You can simply use object spreading for this

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

Here's a working demo

Sign up to request clarification or add additional context in comments.

Comments

0

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]);   
 }

And then the resulting combined style goes into props of your component.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.