Skip to content Skip to sidebar Skip to footer

Passing A Ref From A Child To A Parent In React With Class Component

I have an iFrame in a child component, and want to pass a ref of the iframe to the parent component so I can do a postMessage to the iframe. I am unsure how to implement forwarding

Solution 1:

Here's an example how can you do it

const { forwardRef, useRef, useState, useEffect } = React;

const Child = forwardRef((props, ref) => {
  const computeDataUrl = (value) => {
    return `data:text/html,${encodeURI(value)}`
  }

  const [data, setData] = useState(computeDataUrl('Init'))
    
  const onMessage = ({data, origin}) => {
    setData(computeDataUrl(data));
  }
  
  useEffect(() => {
    const iFrameElement = ref && ref.current;
    
    if(iFrameElement) {
      const iFrameWindow = iFrameElement.contentWindow;
      
      iFrameWindow.addEventListener("message", onMessage, false);
    }
  
    return () => {
      iFrameWindow.removeEventListener("message", onMessage);
    }
  }, [])
  
  return <iframe ref={ref} src={data} width="400" height="300" sandbox="allow-same-origin allow-scripts">
  </iframe>
})

const Parent = () => {
  const ref = useRef();
  
  useEffect(() => {
    
    const iFrameElement = ref && ref.current;
    
    if(iFrameElement) {
      const postMessage = iFrameElement.contentWindow.postMessage;
      postMessage("Message from parent"); 
    }
  
  }, [ref])

  return <Child ref={ref}></Child>
}

ReactDOM.render(
    <Parent />,
    document.getElementById('root')
  );
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

<div id="root"></div>

Solution 2:

If you want your child reference, that's easy...

<ChildComponent
    ref={(instance) => {this.child = instance}}
/>

Then you can call child functions in your parent like this.child.childFunction().

If you want to get your child's child reference, just continue this pattern.

Your child class: Set your grandchild in your render().

render() {
    return (
        <GrandChildComponent
            ref={(instance) => {this.grandchild = instance}}
        />
    );
}

Your parent class: Call the child component's reference's grandchild key.

var grandchild = this.child.grandchild;

Post a Comment for "Passing A Ref From A Child To A Parent In React With Class Component"