Home > Net >  How do I select my CSS module class using document.querySelector?
How do I select my CSS module class using document.querySelector?

Time:10-19

I want to be able to select styles.scrollValue using the document.querySelector()

import { useEffect } from "react";
import styles from "./Navbar.module.scss";

const Navbar = () => {
  const handleScroll = () => {
    document.querySelector(styles.scrollValue).innerHTML = scrollY;
  };
  useEffect(() => {
    document.addEventListener("scroll", handleScroll);
    return () => {
      document.removeEventListener("scroll", handleScroll);
    };
  });
  return (
    <nav className={styles.navbar}>
      <div className={styles.content}>
        <h1 className={styles.scrollValue}>0</h1>
      </div>
    </nav>
  );
};

Running this code I get an error:

TypeError: document.querySelector(...) is null

I know I can add a global class to that element doing this:

className={`${styles.scrollValue} scrollValue`}

But that would ruin the advantage of using CSS Modules.

Is there a way to select the CSS Module class without adding another one to it?

CodePudding user response:

You need to select it as a class,

document.querySelector(`.${styles.scrollValue}`)

Calling styles.property returns a value such as the following,

scrollValue: '_src_styles_module__scrollValue'

So when you call document.querySelector it's looking for _src_styles_module__scrollValue which has no selector type such ., or # which makes it look for an element that would match <_src_styles_module__scrollValue> (in this case). Since there is no element with that name or the hashed name it will return null.

Working demo

  • Related