Something this simple should be easily accomplished, yet I\'m pulling my hair out over how complicated it is.
All I want to do is animate the mounting & unmounti
I know there are a lot of answers here, but I still did not find one that suits my needs. I want:
After many hours of fiddling, I have a solution that works I'd say 90%. I've written the limitation in a comment block in the code below. I'd still love a better solution, but this is the best I've found, including the other solutions here.
const TIMEOUT_DURATION = 80 // Just looked like best balance of silky smooth and stop delaying me.
// Wrap this around any views and they'll fade in and out when mounting /
// unmounting. I tried using and but I
// could not get them to work. There is one major limitation to this approach:
// If a component that's mounted inside of has direct prop changes,
// will think that it's a new component and unmount/mount it. This
// means the inner component will fade out and fade in, and things like cursor
// position in forms will be reset. The solution to this is to abstract
// into a wrapper component.
const Fade: React.FC<{}> = ({ children }) => {
const [ className, setClassName ] = useState('fade')
const [ newChildren, setNewChildren ] = useState(children)
const effectDependency = Array.isArray(children) ? children : [children]
useEffect(() => {
setClassName('fade')
const timerId = setTimeout(() => {
setClassName('fade show')
setNewChildren(children)
}, TIMEOUT_DURATION)
return () => {
clearTimeout(timerId)
}
}, effectDependency)
return {newChildren}
}
If you have a component you want to fade in/out, wrap it in
Ex.
.
Note that this uses react-bootstrap
for the class names and for
, but both could be easily replaced with custom CSS and a regular old