Skip to content

Instantly share code, notes, and snippets.

@SZharkov
Created August 2, 2020 11:04
Show Gist options
  • Save SZharkov/e247e9158b27bc1792751ec475eeac9e to your computer and use it in GitHub Desktop.
Save SZharkov/e247e9158b27bc1792751ec475eeac9e to your computer and use it in GitHub Desktop.
Next.js ClientOnlyPortal
import { useRef, useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
export default function ClientOnlyPortal({ children, selector }) {
const ref = useRef()
const [mounted, setMounted] = useState(false)
useEffect(() => {
ref.current = document.querySelector(selector)
setMounted(true)
}, [selector])
return mounted ? createPortal(children, ref.current) : null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment