Created
March 20, 2020 18:17
-
-
Save JosephScript/3f4b4abe04cbe8aed646ab2d39fc0812 to your computer and use it in GitHub Desktop.
An easy way to use CSS transitions in React to animate a child element in and out
This file contains 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 React, { FC, useEffect, useState, ReactNode } from 'react' | |
import styled from '@emotion/styled' | |
const FadeInAndOut = styled.p` | |
transition: opacity 0.5s; | |
opacity: 0; | |
&.fadeIn { | |
opacity: 1; | |
} | |
` | |
export const Animate: FC = ({ children, ...props }) => { | |
const [child, setChild] = useState<ReactNode>() | |
useEffect(() => { | |
if (children == null) { | |
setTimeout(() => { | |
setChild(children) | |
}, 500) | |
} else { | |
setChild(children) | |
} | |
}, [children]) | |
return ( | |
<FadeInAndOut className={children && 'fadeIn'} {...props}> | |
{child} | |
</FadeInAndOut> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment