-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
44 lines (35 loc) · 1.04 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* eslint-disable import/no-unused-modules */
import {useRef, useState, useEffect} from 'react'
/** Controls the visibility and mounting state of a component using transition effects. */
export const useTransitionVisible = (isOpen: boolean) => {
const refNode = useRef<HTMLDivElement>(null)
const [isMounted, setIsMounted] = useState(isOpen)
const [isVisible, setIsVisible] = useState(isOpen)
useEffect(() => {
if (isOpen) {
setIsMounted(true)
requestAnimationFrame(() => {
requestAnimationFrame(() => {
setIsVisible(true)
})
})
} else {
setIsVisible(false)
}
const handleTransitionEnd = (event: TransitionEvent) => {
if (event.target === refNode.current && !isOpen) {
setIsMounted(false)
}
}
const node = refNode.current
node?.addEventListener('transitionend', handleTransitionEnd)
return () => {
node?.removeEventListener('transitionend', handleTransitionEnd)
}
}, [isOpen])
return {
refNode,
isMounted,
isVisible
}
}