Skip to content

Instantly share code, notes, and snippets.

@MarlonPassos-git
Created September 29, 2023 17:45
Show Gist options
  • Save MarlonPassos-git/438bca73176559fc98480d5dd55cd7ca to your computer and use it in GitHub Desktop.
Save MarlonPassos-git/438bca73176559fc98480d5dd55cd7ca to your computer and use it in GitHub Desktop.
lazy Component
import type { FC, ReactElement } from 'react'
import { useEffect, useState } from 'react'
interface DomContentInterface {
children: ReactElement<any, any> | null
}
const DOMContentLoadedWrapper: FC<DomContentInterface> = ({ children }) => {
const [isReady, setIsReady] = useState(false)
useEffect(() => {
const handleDOMContentLoaded = () => {
setIsReady(true)
}
if (document.readyState === 'complete') {
setIsReady(true)
} else {
document.addEventListener('DOMContentLoaded', handleDOMContentLoaded)
}
return () => {
document.removeEventListener('DOMContentLoaded', handleDOMContentLoaded)
}
}, [])
if (!children) {
return <></>
}
return isReady ? children : <></>
}
export default DOMContentLoadedWrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment