0

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

1

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.

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

1 Comment

Ah that makes sense. I guess that was me forgetting that SASS is just going to get compiled into CSS anyways. Since the background-color is dynamically loaded on the individual component level, this may be one of those cases where inline-styles may actually be appropriate.
0

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.

2 Comments

I know I can set the className like that. My question was whether I could set the style classes programatically instead of manually.
@nao that is programatically. Manually would be setting className="myClass". If you mean setting "styles" programatically instead of making all those different classes then yes inline-styles would be easiest. The way you have explained it above you are trying to do both things at the same time you need to decide to either make classes and append them or build up the styles on a component inline or with styled-components.

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.