score:1

if you are using react-hooks, you can create your custom usedocument hook:

import react, { useeffect, usestate } from 'react'

export const usedocument = () => {
  const [mydocument, setmydocument] = usestate(null)
   
  useeffect(() => {
    setmydocument(document)
  }, [])

  return mydocument
}

in your component:

...
const doc = usedocument()
...

<somecomponent
 ref={doc && doc.body}
 ...
/>
...

score:3

this issue usually happens because when react is rendered on the server. it does not have a document or window object on the server side and those objects are only available on the browser.

try to call the document functions in or after componentdidmount.

componentdidmount(){
  this.setstate({documentloaded:true});
}

somefunction(){
  const { documentloaded } = this.state;
  if(documentloaded){
     // logic using document object
  }
}

Related Query

More Query from same tag