Skip to content

Commit dd4b841

Browse files
authored
[FEATURE] Allow passing ref to the iframe element in react (#25)
#24
1 parent 83d8855 commit dd4b841

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

packages/react/src/components/index.tsx

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
"use client";
22

33
import { type Settings, initialize } from "@open-iframe-resizer/core";
4-
import { type IframeHTMLAttributes, useEffect, useRef } from "react";
4+
import { type IframeHTMLAttributes, forwardRef, useCallback, useEffect, useRef } from "react";
55

66
interface Props extends IframeHTMLAttributes<HTMLIFrameElement>, Partial<Settings> {}
77

8-
export function IframeResizer(props: Props) {
8+
export const IframeResizer = forwardRef<HTMLIFrameElement, Props>((props, forwardedRef) => {
99
const iframeRef = useRef<HTMLIFrameElement>(null);
1010
const { settings, iframeAttributes } = filterProps(props);
1111

@@ -17,8 +17,23 @@ export function IframeResizer(props: Props) {
1717
return () => results.forEach((value) => value.unsubscribe());
1818
}, []);
1919

20-
return <iframe {...iframeAttributes} ref={iframeRef} />;
21-
}
20+
const composedRef = useCallback(
21+
(el: HTMLIFrameElement) => {
22+
iframeRef.current = el;
23+
24+
if (typeof forwardedRef === "function") {
25+
forwardedRef(el);
26+
} else if (forwardedRef) {
27+
forwardedRef.current = el;
28+
}
29+
},
30+
[forwardedRef],
31+
);
32+
33+
return <iframe {...iframeAttributes} ref={composedRef} />;
34+
});
35+
36+
IframeResizer.displayName = "IframeResizer";
2237

2338
function filterProps(props: Props): { iframeAttributes: IframeHTMLAttributes<HTMLIFrameElement>; settings: Partial<Settings> } {
2439
const {

0 commit comments

Comments
 (0)