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

Add react hooks support #108

Closed LosYear closed 3 years ago

LosYear commented 3 years ago

Hi! Thank you for your package

I'm wondering, are there any plans to support React hooks? Something like

const {width, height} = useResizeDetector(ref);

I believe it can be useful nowadays

maslianok commented 3 years ago

Great push, @LosYear :)

I also think it will be a good feature for the library. I'll try to work on it this month

bluenote10 commented 3 years ago

There is also:

Perhaps they can serve as an inspiration.

maslianok commented 3 years ago

Ok, there are too many likes to this feature request, so I can't procrastinate anymore :)

Today I published v6.0.0-alpha.0 that supports a hook approach.

Please, give it a shot:

import { useResizeDetector } from 'react-resize-detector';

const CustomComponent = () => {
  const { width, height, ref } = useResizeDetector();
  return <div ref={ref}>{`${width}x${height}`}</div>;
};

you can pass props as an object to useResizeDetector. For example, useResizeDetector({ refreshMode: 'debounce', refreshRate: 1000 })

maslianok commented 3 years ago

@bluenote10 thanks for the provided links 👍

stefann01 commented 3 years ago

Typescript support? Setting ref={ref} in typescripts it says that

Type 'MutableRefObject<Element | undefined>' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject | null | undefined'. Type 'MutableRefObject<Element | undefined>' is not assignable to type 'RefObject'. Types of property 'current' are incompatible. Type 'Element | undefined' is not assignable to type 'HTMLDivElement | null'. Type 'undefined' is not assignable to type 'HTMLDivElement | null'.

maslianok commented 3 years ago

@stefann01 @SteffeyDev thanks guys for reporting/resolving the issues.

Published in v6.0.1-rc.4