Created
July 21, 2021 20:30
-
-
Save arcticmatt/86432d3ece64db186bf4a054e70a7ed6 to your computer and use it in GitHub Desktop.
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
const NAMES = ["katie", "adam", "jefra"]; | |
function Pill(): JSX.Element { | |
const [name, setName] = useState(NAMES[0]); | |
const nameIndexRef = useRef(0); | |
// 1. Delete name | |
// 2. When name length is 0, increment nameIndex and start adding new name | |
// 3. When new name is finished, go back to step 1 | |
useEffect(() => { | |
function addName() { | |
const interval = setInterval(() => { | |
setName((currName) => { | |
if (currName.length === NAMES[nameIndexRef.current].length) { | |
clearInterval(interval); | |
setTimeout(() => { | |
deleteName(); | |
}, 1000); | |
return currName; | |
} | |
return NAMES[nameIndexRef.current].slice(0, currName.length + 1); | |
}); | |
}, 200); | |
return interval; | |
} | |
function deleteName() { | |
const interval = setInterval(() => { | |
setName((currName) => { | |
if (currName.length === 0) { | |
clearInterval(interval); | |
nameIndexRef.current = (nameIndexRef.current + 1) % NAMES.length; | |
setTimeout(() => { | |
addName(); | |
}, 1000); | |
return currName; | |
} | |
return currName.slice(0, currName.length - 1); | |
}); | |
}, 100); | |
return interval; | |
} | |
const interval = deleteName(); | |
return () => clearInterval(interval); | |
}, []); | |
return ( | |
<div className={styles.pill}> | |
<div>learnwith.io/{name}</div> | |
<div className={joinClasses(styles.blink, styles.cursor)} /> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment