Languages

React - how to add multiple classes to element using CSS modules?

0 points
Asked by:
James-Z
767

How can I add multiple classes to style React component using modules?

My code:

Navbar.jsx file:

import styles from './Navbar.module.scss';

const Navbar = () => {
    return (
        <div className={styles.navbar}>
          //...
        </div>
    );
};

export default Navbar;

Navbar.module.scss file:

div.navbar {
    background: #856361;
}

div.active {
    background: #8c6e6c;
}

What I want to do is to assign multiple classes inside className like this:

<div className={styles.navbar, styles.active}>

How can I do this?

1 answer
0 points
Answered by:
James-Z
767

You can pass multiple classes using Template literals (Template strings).

Quick solution:

className={`${styles.navbar} ${styles.active)`}

Practical example

If you want to pass two classes navbar and active to the className your code would look like this:

import styles from './Navbar.module.scss';


const Navbar = () => {
    return (
        <div className={`${styles.navbar} ${styles.active}`}>
          //...
        </div>
    );
};

export default Navbar;

 

References

  1. Template literals (Template strings) - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join