2

I'm trying to extend HTMLDivElement prototype with a new method. However, I don't want to pollute the HTMLDivElement itself with my methods so I'm trying to create a new class that extends it.

export class ScrollableElement extends HTMLDivElement {
  scrollHorizontal(left: number) {
    this.scrollTo({ left, behavior: 'smooth' });
  }
}

I use this element for scrollable div's ref. However, whenever I try to call this method, I get error saying listRef.scrollHorizontal is not a function.

Is there any way to achieve this?

zilijonas
  • 3,285
  • 3
  • 26
  • 49
  • 3
    Delegation may be a better option: https://stackoverflow.com/questions/24823442/can-you-extend-a-htmldivelement-in-typescript – DemiPixel Oct 07 '21 at 22:09
  • You're using React, why not create a component instead? –  Oct 07 '21 at 22:23

1 Answers1

1

I've managed to do this using delegation as one comment below my question suggested.

Element class:

export class ScrollableElement {
  private _element: HTMLDivElement | null;

  constructor(element: HTMLDivElement | null) {
    this._element = element;
  }

  scrollHorizontal(left: number) {
    this._element?.scrollTo({ left, behavior: 'smooth' });
  }
}

Ref assignment to div:

const [scrollableEl, setScrollableEl] = useState<ScrollableElement | null>(null);

return <div ref={ref => setScrollableEl(new ScrollableElement(ref))} />

function scroll() {
  scrollableEl?.scrollHorizontal(100);
}
zilijonas
  • 3,285
  • 3
  • 26
  • 49