0
votes

Basic question on best practices for dynamically inserting SASS classes with React.

I have a React component with two props: componentId, and color. The components are rendered as a list. Each time they're rendered, I want them to set the component's CSS background color as this.props.backgroundColor.

I understand that I can do this with inline styles, but that that's generally frowned upon due to difficulty maintaining it. I currently have an SCSS file with a number of classes.

How could I dynamically append an SCSS class with the class name this.props.componentId and the color this.props.backgroundColor?

For example, if the component had this.props as

componentId: list-item-123456789
color: #00FFFF

How could I append, from the react component, the following SCSS class to my style.scss file?

.list-item-123456789 {
    background-color: #00FFFF;
}

Is this a job for styled-components? Is this one of those cases where inline-styles is probably the best practice for the job? It feels icky to me to do that just from what I've been reading but I'm not sure how to approach the above solution.

2

2 Answers

1
votes

As you've guessed, this would be a job for styled components or inline-styles. When your React application compiles, all of those SASS files are converted into standard CSS via Webpack (I presume). Thus, once your application has been bundled and deployed, your SASS files are redundant.

0
votes

Inline styles are not the same as just setting a class on an element which you can do if you are going to actually manually create all those style classes.

Just do

<li className={{this.props.componentId}}>Some Item </li>

Make sure your SASS class's are global or in scope for that component.