1

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?

1
  • This has solved my problem. Thank you. Do post this as the answer if possible. Sep 20, 2021 at 14:42

3 Answers 3

1

I believe you need to typecast this as an HTMLElement.

const x = base as HTMLCollectionOf<HTMLElement>
1

Actually, Typescript always tries to suppose everything is Nullish(undefined or null) and would make an error otherwise you must tell it my data is not gonna be nullish. So keep in your mind these rules:

1: Never try to define data as nullish by default.

2: If you broke rule number one, you definitely need to use a condition that tells to typescript this data is not nullish here!

3: Choose the best data type for your data as much as you can and possible.

According to these rules, you did some wrong thing and if you change them you wouldn't see that error again.

You broke rule number 1 when you wrote the code below:

const headerRef = useRef<HTMLDivElement>(null)

Don't pass null here if it is not necessary to be passed.

If you want to change the style of an element with useRef and you don't want to have another reRender(which is mentally in this way), and you want to use typescript, you should use "HTMLElement" as the data type for the useRef state!

and finally try to check everything is right and there is no other problem (tell it to typescript with conditions!)

Suppose you want to change the CSS of a button whenever the 'loading' state would change and you want to do that with useRef and typescript in your react application:

const buttonsRef = useRef<HTMLElement>();
useEffect(() => {
        if (buttonsRef.current !== undefined && loading)
            buttonsRef.current.style.border = "solid 1px red;";
        else if (buttonsRef.current !== undefined && !loading)
            buttonsRef.current.style.border = "solid 1px #dededf;"
    }, [loading]);

There are some other tricks to be used in this way but I just wanted to show you the simplest one and how you should think in typescript.

0

If you're trying to set style from some element using typescript, typescript cannot know if the DOM really exist. You should test if the element is undefined first.

if(base[0] !== undefined ) { base[0].style.backgroundPositionY = offset * 0.2 + "px"; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.