Last active
June 29, 2019 21:58
-
-
Save tmikeschu/1d3685a109a44ec672ead7b563eebcd0 to your computer and use it in GitHub Desktop.
A simple typewriter effect using hooks and emotion
This file contains hidden or 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 { css, cx } from 'emotion'; | |
import React, { useEffect, useState } from 'react'; | |
export default function useTypewriter( | |
text, | |
{ speed = 40, Component = 'p', startingIndex = -30 } = {}, | |
) { | |
// start negative to create a delayed effect to offset the initial transition of the slide | |
const [charIndex, setCharIndex] = useState(startingIndex); | |
useEffect(() => { | |
const type = setTimeout(() => { | |
if (charIndex < text.length) { | |
setCharIndex(i => i + 1); | |
} | |
}, speed); | |
return () => clearTimeout(type); | |
}); | |
return ( | |
<Component | |
className={css` | |
&::after { | |
display: inline-block; | |
content: '|'; | |
animation: blink-cursor 0.75s step-end infinite; | |
} | |
@keyframes blink-cursor { | |
from, | |
to { | |
opacity: 0; | |
} | |
50% { | |
opacity: 1; | |
} | |
} | |
`} | |
> | |
{charIndex > 0 ? text.slice(0, charIndex) : ''} | |
</Component> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment