maslianok / react-resize-detector

A Cross-Browser, Event-based, Element Resize Detection for React
http://maslianok.github.io/react-resize-detector/
MIT License
1.25k stars 91 forks source link

Allow users to specify element type for targetRef to avoid having to cast #161

Closed hsource closed 3 years ago

hsource commented 3 years ago

Motivation

While using this library in Typescript, I noticed that I had to cast targetRef to avoid typing errors.

This code:

          <ResizeDetector handleWidth handleHeight onResize={handleResize}>
            {({ targetRef }) => <div ref={targetRef}>{contents}</div>}
          </ResizeDetector>

Would result in this error:

Type 'RefObject<HTMLElement> | undefined' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
  Type 'RefObject<HTMLElement>' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
    Type 'RefObject<HTMLElement>' is not assignable to type 'RefObject

To workaround it, I had to cast the ref every time. This is a bit verbose though

          <ResizeDetector handleWidth handleHeight onResize={handleResize}>
            {({ targetRef }) => (
              <div ref={targetRef as RefObject<HTMLDivElement>}>{contents}</div>
            )}
          </ResizeDetector>

Fix

I made the ResizeDetector typings take an optional generic type that defaults to HTMLElement (same as today). This way, instead of having to do an explicit cast, we can just instantiate the <ResizeDetector> with that generic type.

Now, I can just write:

          <ResizeDetector<HTMLDivElement>
            handleWidth
            handleHeight
            onResize={handleResize}
          >
            {({ targetRef }) => <div ref={targetRef}>{contents}</div>}
          </ResizeDetector>

Testing

Installed package on my own project and ensured that it was working.

maslianok commented 3 years ago

Thank you for your efforts! 💪

Merged and published in v6.7.3