Search code examples
javascripthtmlreactjstypescriptprototype

create new class from HTMLDivElement and extend its prototype


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?


Solution

  • 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);
    }