import React from 'react'
function MyComponent() {
return (
<div>
<p style={{color: 'red'}}>Testing to see if my component renders!</p>
</div>
)
}
export default MyComponent;
Now, let’s create a file CustomIframe.js
import React, { useState } from 'react'
import { createPortal } from 'react-dom'
const CustomIframe = ({
children,
...props
}) => {
const [contentRef, setContentRef] = useState(null)
const mountNode =
contentRef?.contentWindow?.document?.body
return (
<iframe {...props} ref={setContentRef}>
{mountNode && createPortal(children, mountNode)}
</iframe>
)
}
export default CustomIframe;
What is ref in return doing ? and Why it's needed ? and Why put setContentRef instead contentRef in ref={}?
Other than this, Why {...props} is present in iframe tag, when they are not consumed anywhere?
I tried finding ref online, only got to know about useRef hook, not ref
CodePudding user response:
setContentRef
will assign iframe element reference tocontentRef
so you could access native methods and properties available in the iframe such ascontentWindow
{...props}
will spread out all the values in the props as attributes to the iframe element