Using kebab-case CSS classnames in CSS/SASS modules when using Next js
Asked Answered
S

6

9

I am using SCSS modules for my components in React/Next.js but I can't figure out how to import kebab-case classes.

At the moment, I am just writing all my SCSS classes in camelCase but this isn't ideal as this means I cannot make use of SCSS cascading.

(I'm still learning React am I'm not so great at making dynamic components myself so I am sticking to React Strap for now.)

Essentially, I want to write

.company-logo

instead of:

.companyLogo

EDIT: className={styles['company-logo']} causes an unexpected token error

Here is my Component:

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

const NavComponent = (props) => {
  const [isOpen, setIsOpen] = useState(false);

  const toggle = () => setIsOpen(!isOpen);

  return (
    <div>
      <img src="../ss-logo.png" alt="Logo" className={styles.companyLogo}/>
    </div>
  );
}

export default NavComponent;

And my SCSS:

.companyLogo {
  height: 3rem;
}
Stadium answered 14/5, 2020 at 10:20 Comment(1)
Did u solve this.?Allison
N
17
className={styles['company-logo']}

should be what you want.

Northumberland answered 14/5, 2020 at 10:26 Comment(1)
Nope, I tried that. It causes an "unexpected token error" :/Stadium
R
5

You can use the object key [] syntax.

<img src="..." className={styles['company-logo']}`
Rambo answered 14/5, 2020 at 10:26 Comment(1)
Nope, I tried that. It causes an "unexpected token error" :/Stadium
C
3
<img src="../ss-logo.png" alt="Logo" className={`${style['company-logo']}`}/>

Cognac answered 28/10, 2021 at 19:23 Comment(0)
W
2

Inline:

<img src="../ss-logo.png" alt="Logo" className={`${styles["company-logo"]}`}/>

Variable:

var logo = classNames({
  [`${styles["company-logo"]}`]: true,
});

return (
  <div>
    <img src="../ss-logo.png" alt="Logo" className={logo} />
  </div>
)
Whitlow answered 23/8, 2022 at 3:58 Comment(0)
D
2

Yes but you will not have autocomplete and go to definition, i am just naming them camelCase in module.css :)

Deidradeidre answered 7/3 at 23:48 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Kaykaya
C
1

You can use the bracket notation [] to access object with a dash - separator:

<img className={styles['company-logo']}/>

Additionally, if you want to apply multiple class names, you can use template literals:

<img className={`${styles['company-logo']} ${styles['personal-logo']}`/>
Camfort answered 26/1 at 16:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.