Last active
March 25, 2019 16:59
-
-
Save crtr0/3de3977ea6e5e50cc3cb4b6427d6e883 to your computer and use it in GitHub Desktop.
React component for typing out words (uses Hooks)
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 { useState, useEffect } from 'react' | |
// wordList is expected to be an array | |
const TypeText = ({ wordList }) => { | |
const words = wordList | |
const [text, setText] = useState(null) | |
let wordIndex = 0 | |
let typingIndex = 0 | |
let timer | |
function printLetter() { | |
let foo = '' | |
const wordLength = words[wordIndex].length | |
let lettersTo = (typingIndex > wordLength - 1 ? wordLength * 2 - typingIndex : typingIndex) | |
for (let i = 0; i < lettersTo; i++) { | |
foo += words[wordIndex][i] | |
} | |
typingIndex++ | |
setText(foo) | |
nextLetter() | |
} | |
const nextLetter = () => { | |
const wordLength = words[wordIndex].length | |
if (typingIndex === wordLength * 2) { | |
typingIndex = 0 | |
wordIndex = (wordIndex + 1) % words.length | |
return nextLetter() | |
} | |
let wait | |
// pause at the beginning and end of typing out a word | |
if (typingIndex === 1 || typingIndex === words[wordIndex].length + 1) { | |
wait = 900 | |
} | |
// erase quickly | |
else if (typingIndex > words[wordIndex].length) { | |
wait = 50 | |
} | |
// typing forward speed | |
else { | |
wait = 100 | |
} | |
timer = setTimeout(printLetter, wait) | |
} | |
useEffect(() => { | |
nextLetter() | |
// cleanup will only run on unmount | |
return function cleanup() { | |
clearTimeout(timer) | |
} | |
}, []) | |
return ( | |
text | |
) | |
} | |
export default TypeText |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment