Search code examples
reactjsreact-typescripttsxuse-ref

Typescript error while modifying style with useRef


The following is my tsx file. The following code works fine in plain js. I am trying to migrate my project to typescript.

import React, { useRef } from "react";

const HomeHeader = (): JSX.Element => {
  const headerRef = useRef<HTMLDivElement>(null);

  const handleScroll = () => {
    if (headerRef.current) {
      try {
        const offset = window.pageYOffset;
        const base = headerRef.current.children;
        base[0].style.backgroundPositionY = offset * 0.2 + "px";
      } catch (e) {
        console.warn("Error");
      }
    }
  };

  window.addEventListener("scroll", handleScroll);

  return (
    <header>
      <div className="header--home" ref={headerRef}>
        <div className="header--home-overlay" />
    </header>
  );
};

export default HomeHeader;

This is the error Error

How can i fix this?


Solution

  • I believe you need to typecast this as an HTMLElement.

    const x = base as HTMLCollectionOf<HTMLElement>