UP | HOME

React, TypeScript and scrollInToView

Let's say you have a list of components (for example: articles, comments, shopping items) that being refreshed during pagination, and you want to scroll to the top of that list.

I usually put an empty div on top of that list, and gave it a ref, later on I can use the scrollIntoView() method to scroll the page into that div.

In TypeScript, you'll have more extra steps to do so, seems to be annoying, but it's actually very helpful because you can take advantages of the type system.

First, define a ref like this:

class ListArticles extends React.Component {
  private scrollAnchorRef: RefObject<HTMLDivElement>;

  constructor(props) {
    super(props);
    this.scrollAnchorRef = React.createRef();
  }

  render() {
    <div ref={this.scrollAnchorRef}>
      ...
    </div>
  }
}

It's recommended to use HTMLDivElement instead of a generic HTMLElement type when defining a ref, because it will help the compiler narrow down the type so you'll have better suggestion in the next step.

Now, when you finish loading data and want to scroll, you can do:

this.scrollAnchorRef.current.scrollIntoView()

And you'll get an error message says:

TS2531: Object is possibly 'null'

The reason is, RefObject<T>.current has the type of T | null, because React will actually set an element's ref into null when it re-render, and if you're trying to scroll during re-render, you'll run into problems.

The solution is simple, add an existent check:

const anchor = this.scrollAnchorRef;
if (anchor) anchor.scrollIntoView();

This is how type saved your butt.

Date: 2019-01-31 Thu 00:00

Author: Huy Tran

Created: 2019-04-22 Mon 14:41