46

In my component, I have the following code to scroll to the bottom of the page:

const el = useRef(null);

useEffect(() => {
    if (el.current === null) { }
    else
        el!.current!.scrollIntoView({ block: 'end', behavior: 'smooth' });

    if (props.loading != true)
        props.fetchFeedbackTaskPageData(submissionId);

}, [])

This el ref is attached to a div (at the bottom of the page) like this:

<div id={'el'} ref={el}></div>

However, I am receiving the following error:

Property 'scrollIntoView' does not exist on type 'never'. TS2339

When I was not using !, I was receiving this error:

Object is possibly 'null'. TS2531

I checked many posts on this issue but did not see how to handle this in react when using useRef and scrollIntoView. Any ideas?

2
  • how you are using ref? Jul 14, 2019 at 15:06
  • @ravibagul91 el ref is attacthed to a div (at the bottom of the page): <div id={'el'} ref={el}></div>
    – renakre
    Jul 14, 2019 at 15:08

2 Answers 2

100

For anyone reading this in 2020 its

const el = useRef<null | HTMLDivElement>(null); 

and no longer:

const el = useRef<null | HTMLElement>(null);
3
  • 1
    I'm wondering why we should useRef instead of directly document.findElementById()
    – daCoda
    Sep 27, 2022 at 8:01
  • @daCoda It has to do with the Virtual DOM: reactjs.org/docs/faq-internals.html
    – brogrammer
    Nov 22, 2022 at 22:14
  • Great contribution. How could this be adapted for an array of html elements? eg. ts const cardRefs = useRef([]); cardRefs.current = cardsPerPage.map( (card, i) => cardRefs.current[i] ?? createRef() );
    – Lauro235
    Feb 21 at 22:21
38

You have to tell useRef what types other than null it will be assigned to, e.g. useRef<null | number>(null) or in your case useRef<null | HTMLElement>(null).

The problem is that by assigning null as a default value to the ref, typescript can only guess that the type of the ref will be that of it's initial value (null) - which is why you're getting the errors you mentioned. Generally speaking, refs don't have to be DOM components, so useRef's type definition does not assume that it will be assigned to one.

4
  • 2
    Thanks for the reply! But, this is the problem I am facing. In all tutorials, ref(null) is used. I do no know how to define it otherwise.
    – renakre
    Jul 14, 2019 at 15:03
  • Oh sorry - I think my comment was reformatted, let me fix that real quick Jul 14, 2019 at 15:07
  • 1
    Instead of number I was supposed to put HtmlElement. Thanks again for the help on a vacation day.. :)
    – renakre
    Jul 14, 2019 at 15:15
  • 1
    For anyone following this, it's HTMLElement. Dec 13, 2019 at 10:07

Your Answer

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

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