Home > Enterprise >  What ref does and why it's necessary in iframes?
What ref does and why it's necessary in iframes?

Time:12-12

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;
  1. What is ref in return doing ? and Why it's needed ? and Why put setContentRef instead contentRef in ref={}?

  2. 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:

  1. setContentRef will assign iframe element reference to contentRef so you could access native methods and properties available in the iframe such as contentWindow

  2. {...props} will spread out all the values in the props as attributes to the iframe element

  • Related