Refactor Portal
This commit is contained in:
parent
4d439ba14b
commit
25f0d393c2
1 changed files with 12 additions and 33 deletions
|
|
@ -1,43 +1,22 @@
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import React, { useEffect, useRef } from 'react'
|
||||||
import { createPortal, render } from 'react-dom'
|
import { createPortal } from 'react-dom'
|
||||||
|
|
||||||
const Portal = ({ children }) => {
|
const modalRoot = document.querySelector('#modal') as HTMLElement
|
||||||
const el = document.createElement('div')
|
|
||||||
el.classList.add('modal_content')
|
|
||||||
|
|
||||||
let modalRoot = document.getElementById('modal')
|
const Portal: React.FC<{}> = ({ children }) => {
|
||||||
|
const modalContent = document.createElement('div')
|
||||||
|
modalContent.classList.add('modal_content')
|
||||||
|
|
||||||
if (!modalRoot) {
|
const el = useRef(modalContent)
|
||||||
modalRoot = document.createElement('div')
|
|
||||||
modalRoot.setAttribute('id', 'modal')
|
|
||||||
document.body.appendChild(modalRoot)
|
|
||||||
}
|
|
||||||
|
|
||||||
const [val, setVal] = useState(true)
|
|
||||||
|
|
||||||
const modalDiv = useRef(null)
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!modalDiv.current) {
|
const current = el.current
|
||||||
modalDiv.current = el
|
|
||||||
setVal(!val)
|
|
||||||
}
|
|
||||||
}, [modalDiv])
|
|
||||||
|
|
||||||
useEffect(() => {
|
modalRoot!.appendChild(current)
|
||||||
modalRoot.appendChild(modalDiv.current)
|
return () => void modalRoot!.removeChild(current)
|
||||||
return () => {
|
}, [])
|
||||||
document.body.classList.remove('no-scroll')
|
|
||||||
return modalRoot.removeChild(modalDiv.current)
|
|
||||||
}
|
|
||||||
}, [modalDiv, modalRoot])
|
|
||||||
|
|
||||||
if (modalDiv.current) {
|
return createPortal(children, el.current)
|
||||||
document.body.classList.add('no-scroll')
|
|
||||||
return createPortal(children, modalDiv.current)
|
|
||||||
}
|
|
||||||
|
|
||||||
return null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default Portal
|
export default Portal
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue