Skip to content

Conversation

@hsource
Copy link
Contributor

@hsource hsource commented May 31, 2021

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 maslianok merged commit ce726c3 into maslianok:master Jun 23, 2021
@maslianok
Copy link
Owner

Thank you for your efforts! 💪

Merged and published in v6.7.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants