Skip to content

Instantly share code, notes, and snippets.

@JosephScript
Created March 20, 2020 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosephScript/3f4b4abe04cbe8aed646ab2d39fc0812 to your computer and use it in GitHub Desktop.
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
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