0
const [contentRef, setContentRef] = useState<any>(null);

const doc = contentRef?.contentWindow?.document;
const mountNode = doc?.body;
const insertionTarget = doc?.head;

  return (
    <Box
      as="iframe"
      ref={setContentRef}
      {...props}
    >
      {* some code here *}
    </Box>

Recently while working with iframes and @emotion/react i came across this code but I am not sure about using useState for accessing DOM node. when I console.log(contentRef) it returns iframe DOM node.

Can someone please explain how is this working and how it is different from using useRef().

Ziyad
  • 31
  • 3

1 Answers1

0

What you see there is a "callback ref".

Instead of passing a ref attribute created by createRef(), you pass a function. The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere.

setContentRef is a function that accepts the new state value. So the DOM node is passed to the setState call after its rendered. You will be able to access the DOM node in contentRef state.

Shreshth
  • 880
  • 7
  • 11