A React hooks for observing an element resizing and clicking outside
npm i react-ref-observe
import * as React from "react";
import { observeResize, observeClickOutside } from "react-ref-observe";
export const Observers = () => {
const firstRef = React.useRef();
const secondRef = React.useRef();
const [clicks, setClicks] = React.useReducer(c => c + 1, 0);
const firstSize = observeResize(firstRef);
observeClickOutside([secondRef], setClicks);
return (
<>
<div ref={firstRef}>
width: {firstSize.width}, height: {firstSize.height}
</div>
<div ref={secondRef}>Clicks outside: {clicks}</div>
</>
);
};
Observes element resizing. Uses resize-observer-polyfill
- ref - React reference to a DOM element
- callback optional - callback function, taking argument
{width, height}
Returns an object {width: Number, height: Number}
Observes clicks outside an element
- refs - Array of react references to DOM elements
- callback - callback function, taking click or touch event argument