0

I'm trying to add css classes dynamically.

I have a array of colors that i want to get random color each time component rendered.

Here is what i did :

import styles from './UsersBoxItem.module.scss'
let colors = ['red', 'blue', 'green', 'pink', 'orange'];

class UsersBoxItem extends Component {
    render() {
        let colorClass = colors[Math.floor(Math.random() * colors.length)];
        colors = colors.filter(item => item !== colorClass)
        return (
            <div className={`${styles.box} ${styles.colorClass}`}>

I'm using css-modules but this ${styles.colorClass} won't work and i got undefined.

Here's my code : https://codesandbox.io/embed/cocky-cloud-lomzr

Any ideas ? Thanks

6
  • 1
    use colorClass instead styles.colorClass Commented Sep 9, 2019 at 13:02
  • but something like this won't work ? .box { width: 35%; &.green{ background: linear-gradient(to bottom right, $success 40%, $secondary 100%); } } @NicolòCozzani Commented Sep 9, 2019 at 13:05
  • Can you create a minimal reproducible example, on StackBlitz or CodeSandbox? Commented Sep 9, 2019 at 13:20
  • 1
    sure : codesandbox.io/embed/cocky-cloud-lomzr @SungM.Kim Commented Sep 9, 2019 at 13:33
  • Why do you have colors = colors.filter(item => item !== colorClass) line? Commented Sep 9, 2019 at 13:40

2 Answers 2

3

@Sung M. Kim solution work ok, I do not think that what do you want.

https://codesandbox.io/s/thirsty-lewin-k3j1y

enter image description here

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

1 Comment

I see what you are trying to do now @Enzo.
1

You'd need to add actual class declarations in your CSS.

.red {
  color: red;
}
.blue {
  color: blue;
}
.green {
  color: green;
}
.pink {
  color: pink;
}
.orange {
  color: orange;
}

Edit so.answer.57854561

Forked sandbox working

1 Comment

but in local scss file it's not possible ?

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.