Skip to content

Instantly share code, notes, and snippets.

@abecus
Last active January 12, 2022 10:02
Show Gist options
  • Save abecus/7d20f05a140e99088d9f37517bd594c3 to your computer and use it in GitHub Desktop.
Save abecus/7d20f05a140e99088d9f37517bd594c3 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from "react";
const words = ["Developer", "Programmer."];
export default function Home() {
const [index, setIndex] = useState(0);
const [subIndex, setSubIndex] = useState(0);
const [blink, setBlink] = useState(true);
const [reverse, setReverse] = useState(false);
// typeWriter
useEffect(() => {
if (index === words.length - 1 && subIndex === words[index].length) {
return;
}
if (
subIndex === words[index].length + 1 &&
index !== words.length - 1 &&
!reverse
) {
setReverse(true);
return;
}
if (subIndex === 0 && reverse) {
setReverse(false);
setIndex((prev) => prev + 1);
return;
}
const timeout = setTimeout(() => {
setSubIndex((prev) => prev + (reverse ? -1 : 1));
}, Math.max(reverse ? 75 : subIndex === words[index].length ? 1000 :
150, parseInt(Math.random() * 350)));
return () => clearTimeout(timeout);
}, [subIndex, index, reverse]);
// blinker
useEffect(() => {
const timeout2 = setTimeout(() => {
setBlink((prev) => !prev);
}, 500);
return () => clearTimeout(timeout2);
}, [blink]);
return (
<>
<h1>
The {`${words[index].substring(0, subIndex)}${blink ? "|" : " "}`}
</h1>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment