Created
August 2, 2020 11:04
-
-
Save SZharkov/e247e9158b27bc1792751ec475eeac9e to your computer and use it in GitHub Desktop.
Next.js ClientOnlyPortal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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