react-ref-boundary
v1.1.0
Published
React context for grouping react references by boundary in react dom, native and web. Ideal for group references for contains checks when using react portals
Maintainers
Readme
react-ref-boundary
React context for grouping react references by boundary in react dom, native and web. Ideal for group references for contains checks when using react portals.
npm install react-ref-boundary reactThe package requires React 16.8 or newer and Node.js 16 or newer.
Example 1
import { Fragment, useRef as useReactRef, type RefObject } from "react";
import { BoundaryProvider, useRef, useBoundary, type BoundaryRef } from "react-ref-boundary";
function NonBoundaryComponent() {
const ref = useReactRef<HTMLDivElement>(null);
return <div ref={ref} />;
}
function BoundaryComponent() {
const ref = useRef<HTMLDivElement>(null);
return <div ref={ref} />;
}
function BoundaryChecker() {
const boundary = useBoundary();
return (
<button
onClick={(event) => {
if (
!boundary.refs.some(
(ref) => isContainmentRef(ref) && ref.current && ref.current.contains(event.target as Node),
)
) {
// outside all of the references
}
}}
/>
);
}
function isContainmentRef(ref: BoundaryRef): ref is RefObject<{ contains(target: Node): boolean }> {
return (
typeof ref.current === "object" &&
ref.current !== null &&
"contains" in ref.current &&
typeof (ref.current as { contains?: unknown }).contains === "function"
);
}
function BoundaryReporter({ getRefs }: { getRefs: (refs: readonly BoundaryRef[]) => void }) {
const boundary = useBoundary();
getRefs(boundary.refs);
return <Fragment />;
}
export default function App() {
return (
<BoundaryProvider>
<BoundaryComponent />
<NonBoundaryComponent />
<BoundaryComponent />
<BoundaryChecker />
<BoundaryReporter getRefs={(refs) => console.log(refs.length)} />
</BoundaryProvider>
);
}Testing
See local tests and manual Android/iOS CI for the compatibility profiles, test commands, and optional GitHub Actions runs.
