Typing simulation using SetInterval

Live Demo
Code: TypingSimulationSetInterval.jsx
import { useState, useEffect } from "react";
export default function TypingSimulationSetInterval() {
const stringToType = "This is a typing simulation example using React and Tailwind CSS.";
const [displayedText, setDisplayedText] = useState("");
useEffect(() => {
let idx = 0;
const interval = setInterval(() => {
if (idx >= stringToType.length) {
clearInterval(interval);
return;
}
// append the next character
setDisplayedText(stringToType.slice(0, ++idx));
}, 125);
return () => clearInterval(interval);
}, []);
return (
<div className="font-mono text-lg whitespace-pre-wrap">
{displayedText}
<span className="inline-block w-1 h-4 bg-gray-900 ml-1 animate-pulse" />
</div>
);
}

Typing simulation using CSS keyframes

Live Demo
This is a typing simulation example using React and Tailwind CSS.
Code: TypingSimulationKeyframes.jsx
import { useState, useEffect } from "react";
export default function TypingSimulationKeyframes() {
const stringToType = "This is a typing simulation example using React and Tailwind CSS.";
const duration = stringToType.length * 0.125;
return (
<>
<div
className="font-mono text-lg whitespace-nowrap overflow-hidden border-r-2 border-gray-900"
style={{
animation: `typing ${duration}s steps(${stringToType.length}, end) forwards, blink .75s step-end infinite`
}}
>
{stringToType}
</div>
<style jsx global>{`
@keyframes typing {
from { width: 0; }
to { width: ${stringToType.length}ch; }
}
@keyframes blink {
0%, 100% { border-color: transparent; }
50% { border-color: currentColor; }
}
`}</style>
</>
);
}