Skip to content

Commit 81ea22f

Browse files
committed
fix: fix onLoad props issue. #6
1 parent d502b40 commit 81ea22f

File tree

2 files changed

+50
-11
lines changed

2 files changed

+50
-11
lines changed

core/README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,34 @@ export default function Demo() {
192192
}
193193
```
194194

195+
## Event
196+
197+
```tsx mdx:preview
198+
import React, { useEffect, useState, Fragment } from 'react';
199+
import IFrame, { useFrame } from '@uiw/react-iframe';
200+
201+
const InnerComponent = () => {
202+
// Hook returns iframe's window and document instances from Frame context
203+
const { document, window } = useFrame();
204+
return (
205+
<div>
206+
<div>Hello World!</div>
207+
</div>
208+
);
209+
};
210+
211+
export default function Demo() {
212+
const onLoad = (evn) => {
213+
console.log("iframe loaded successfully!", evn)
214+
}
215+
return (
216+
<IFrame onLoad={onLoad}>
217+
<InnerComponent />
218+
</IFrame>
219+
);
220+
}
221+
```
222+
195223
## Props
196224

197225
```ts

core/src/index.tsx

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useCallback, useEffect, useState, forwardRef, useImperativeHandle } from 'react';
1+
import { useCallback, useEffect, useState, forwardRef, useImperativeHandle, useMemo, useRef } from 'react';
22
import { createPortal } from 'react-dom';
33
import { FrameContext } from './Context';
44

@@ -46,16 +46,27 @@ const IFrame = forwardRef<HTMLIFrameElement, IFrameProps>(
4646
}
4747
return doc?.body;
4848
};
49-
const handleLoad = useCallback(() => {
50-
/**
51-
* In certain situations on a cold cache DOMContentLoaded never gets called
52-
* fallback to an interval to check if that's the case
53-
*/
54-
const loadCheck = () => setInterval(() => handleLoad(), 500);
55-
clearInterval(loadCheck());
56-
// Bail update as some browsers will trigger on both DOMContentLoaded & onLoad ala firefox
57-
if (!iframeLoaded) {
58-
setIframeLoaded(true);
49+
const evnRef = useRef<React.SyntheticEvent<HTMLIFrameElement, Event>>();
50+
const handleLoad = useCallback<(evn: React.SyntheticEvent<HTMLIFrameElement, Event> | Event) => void>(
51+
(evn) => {
52+
evnRef.current = evn as React.SyntheticEvent<HTMLIFrameElement, Event>;
53+
/**
54+
* In certain situations on a cold cache DOMContentLoaded never gets called
55+
* fallback to an interval to check if that's the case
56+
*/
57+
const loadCheck = () => setInterval(() => handleLoad(evn), 500);
58+
clearInterval(loadCheck());
59+
// Bail update as some browsers will trigger on both DOMContentLoaded & onLoad ala firefox
60+
if (!iframeLoaded) {
61+
setIframeLoaded(true);
62+
}
63+
},
64+
[iframeLoaded],
65+
);
66+
67+
useMemo(() => {
68+
if (!src && other.onLoad && iframeLoaded) {
69+
other.onLoad(evnRef.current!);
5970
}
6071
}, [iframeLoaded]);
6172

0 commit comments

Comments
 (0)