8

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?

1
  • 1
    Whats inside of ./Navbar.module.scss (and what is contained in styles.scrollValue by that definition)? It should be a css selector. Please add the relevant contents of ./Navbar.module.scss to your question. Commented Oct 18, 2021 at 14:51

1 Answer 1

15

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

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

Comments

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.