reactjssass

How to add multiple class names to an html element when using scss in React


I have a styles.module.scss file and a react component. How can add multiple class names from the styles to ONE HTML element?

Below is my code:

/styles/styles.module.scss file

.gridContainer {
  display: grid;
  gap: 2em;
  grid-template-columns: 1fr 25em;
  grid-template-rows: auto;
}

.gridItem {
  display: flex;
  flex-flow: column;
}

.imageWithText {
  border: 1px solid #4338ca;
  border-radius: 1.6rem;
  align-self: start;
}

/pages/infoPage.tsx file

import styles from "../styles/styles.module.scss";

export default function InfoPage({}: PageProps) {
  <div className={styles.gridContainer}>
    <div className={styles.gridItem}>
      ...
    </div>
    
    {/* I have added TWO style selectors here */}
    <div className={(styles.gridItem, styles.imageWithText)}>
      ...
    </div>
  </div>
}

When I run this code, the div with TWO style selectors does not work as expected. The second classname={styles.gridItem} does not take the scss styles from the .gridItem selector. This div takes the styling only from the .imageWithText.

EXPECTED BEHAVIOR: I want the styles for both the .gridItem and the .imageWithText to apply to the second div.

I believe I am not writing the multiple selectors in the HTML element correctly and this has possibly got something to do with the way Scss works.


Solution

  • You can try with backtic character (`), so your code :

     <div className={`${styles.gridItem} ${styles.imageWithText}`}>