How do I select my CSS module class using document.querySelector?
Asked Answered
B

1

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?

Bearded answered 18/10, 2021 at 14:26 Comment(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.Nuncle
D
14

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

Dunnite answered 18/10, 2021 at 15:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.