0

In my React app, I'm trying to use getComputedStyle and getPropertyValue for my component, but it fails to execute because it doesn't seem to recognize my element. I get TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element

const [dashboardToggle, setDashboardToggle] = useState(false);

  const boardElement = document.getElementsByClassName("dashboard");
  const boardPosition = window
    .getComputedStyle(boardElement[0])
    .getPropertyValue("position");
    

  console.log("this" + boardElement);
  console.log("this" + boardPosition);

return (<div className="App"><AnimatePresence>
        {dashboardToggle && (
          <Dashboard
            className="dashboard"
            dashboardToggle={dashboardToggle}
          ></Dashboard>
        )}
      </AnimatePresence>)
    </div>

When I console log boardElement, I get [object HTMLCollection]. I assume boardElement[0] should be an element param for getComputedStyle.

What seems to be the problem here?

Patorikku
  • 61
  • 8
  • 1
    *"When I console log `boardElement`, I get `[object HTMLCollection]`. I assume `boardElement[0]` should be an element param for `getComputedStyle`."* It would be **if** there were any entries in the collection, but it would appear there aren't, so `boardElement[0]` is `undefined`, which isn't an element. It looks like you're looking for the element before it exists (because it hasn't been rendered yet). – T.J. Crowder Aug 16 '21 at 09:53
  • 1
    As a side note, though, rather than querying the DOM to access that element, use a [ref](https://reactjs.org/docs/refs-and-the-dom.html#gatsby-focus-wrapper). You also need to wrap the code that uses the element in a callback (`useEffect` or `useLayoutEffect`). (You also have a syntax error -- the `` at the end should be *before* the closing `)`.) – T.J. Crowder Aug 16 '21 at 09:55
  • 1
    [Here's an example](https://pastebin.com/S453XhrE) of that code using `useEffect` and a ref. – T.J. Crowder Aug 16 '21 at 10:01

0 Answers0