Streaming Text
AI & ChatCharacter-by-character text streaming display.
Preview
Usage
example.jsx
import { StreamingText } from "@/components/ui/streaming-text";
export default function Example() {
return <StreamingText />;
}Source Code
Copy this file into components/ui/streaming-text.jsx in your project.
streaming-text.jsx
"use client";
import { forwardRef, useState, useEffect } from "react";
import { cn } from "@/lib/utils";
const StreamingText = forwardRef(({ className, text = "", speed = 20, onComplete, ...props }, ref) => {
const [displayed, setDisplayed] = useState("");
useEffect(() => {
setDisplayed("");
let i = 0;
const timer = setInterval(() => {
if (i < text.length) { setDisplayed((p) => p + text[i]); i++; }
else { clearInterval(timer); onComplete?.(); }
}, speed);
return () => clearInterval(timer);
}, [text, speed]);
return <span ref={ref} className={cn("whitespace-pre-wrap", className)} {...props}>{displayed}<span className="inline-block w-0.5 h-4 bg-current animate-pulse ml-0.5 align-text-bottom" /></span>;
});
StreamingText.displayName = "StreamingText";
export { StreamingText };
Quick Install
Make sure you have the cn() utility set up. It requires clsx and tailwind-merge.
npm install clsx tailwind-merge