the-geeky-codes-high-resolution-logo-color-on-transparent-background geeky code red logo
  • Home
  • AI
    AIShow More
    generate vector icons
    Generate Vector Icons with ChatGPT DALLE 3: A Comprehensive Guide
    14 Min Read
    Dalle 3
    Dalle 3: A Step-by-Step Guide to Mastering AI Art Generation
    4 Min Read
    5 Best AI Tools to Convert Images to Video Animations
    5 Best AI Tools to Convert Images to Video Animations
    8 Min Read
    Exploring the Impressive Mistral 7B Model
    Exploring the Impressive Mistral 7B Model for Text Summarization and Coding
    6 Min Read
    The AI Revolution this week
    Must Read – The AI Revolution this week 30 Sep 2023: Integrating AI Tools into Everyday Life
    6 Min Read
  • Tutorial
    • React js
    • Python
    • Javascript
  • AI Tools
Reading: Creating a Typewriter Effect in React Tailwind
Share
the geeky codesthe geeky codes
Aa
  • AI
  • AI Tools
  • Javascript
  • Python
  • React js
  • Advertise
Search
  • Categories
    • AI
    • AI Tools
    • Javascript
    • Python
    • React js
  • More
    • Advertise
Follow US
Copyright ©2023 The Geeky codes. All Rights Reserved.
the geeky codes > Blog > Tutorial > React js > Creating a Typewriter Effect in React Tailwind
TutorialReact js

Creating a Typewriter Effect in React Tailwind

thegeekycodes By thegeekycodes 30 September 2023 5 Min Read
Creating a Typewriter Effect in React Tailwind
SHARE

Creating a Typewriter Effect in React Tailwind, where text appears character by character, can be an engaging way to present content to users. It brings a dynamic flair, reminiscent of vintage typewriters, to modern web designs. In this tutorial, we’ll build a vertical tab component in React that displays content with a typewriter effect using TailwindCSS for aesthetics.

Contents
PrerequisitesSetupInitialize a new React project and incorporate TailwindCSS:Vertical Tabs ComponentCreating a Typewriter Effect in React Tailwind – Complete Code
Vite React TS

Prerequisites

  • A basic understanding of React and JavaScript.
  • Node.js and npm are installed on your machine.

Setup

Initialize a new React project and incorporate TailwindCSS:

Add Tailwind to your React project by following the documentation: Setup TailwindCSS with React

npx create-react-app typewriter-tabs
cd typewriter-tabs
npm install tailwindcss

Vertical Tabs Component

  • Inside the src directory, craft a file titled VerticalTabs.js.
  • Import the necessary modules and state the sample tab content:
// VerticalTabs.js
import React, { useState, useEffect, useRef, RefObject } from "react";

const tabs = [
    {
        id: 1,
        title: "Python",
        content: `
            Python is an interpreted, high-level and general-purpose programming language.`,
    },
    {
        id: 2,
        title: "JavaScript",
        content: `
            JavaScript, often abbreviated as JS, is a programming language that conforms to the 
            ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and 
            multi-paradigm.`,
    },
    {
        id: 3,
        title: "Go (Golang)",
        content: `
            Go, also known as Golang, is a statically typed, compiled programming language designed 
            at Google by Robert Griesemer, Rob Pike, and Ken Thompson. `,
    },
];

Implement the typewriter effect using useEffect:

useEffect(() => {
    // Split the content of the active tab into individual characters.
    const characters = tabs[activeTab].content.split('');
    
    // Reset the typewriter content to an empty string.
    setTypewriterContent('');

    // Initialize the index for the character to be displayed.
    let charIndex = 0;

    // Set an interval to repeatedly execute the function.
    const interval = setInterval(() => {
      
      // Check if there are more characters to be displayed.
      if (charIndex < characters.length) {
        
        // Update the displayed content by appending the next character.
        setTypewriterContent(prevContent => `${prevContent}${characters[charIndex]}`);
        
        // Increment the index for the next character.
        charIndex++;
      } else {
        // If all characters have been displayed, clear the interval.
        clearInterval(interval);
      }
      
    }, 50); // The interval is set to 50ms, so a new character is appended every 50ms.

    // Clear the interval when the component is unmounted or when the active tab changes.
    return () => clearInterval(interval); 
  }, [activeTab]);  // This effect depends on the activeTab state, so it reruns when activeTab changes.

Creating a Typewriter Effect in React Tailwind – Complete Code

// VerticalTabs.js
import { useState, useEffect } from "react";

const tabs = [
    {
        id: 1,
        title: "Python",
        content: `
            Python is an interpreted, high-level and general-purpose programming language. 
            Created in the late 1980s by Guido van Rossum, Python's design philosophy emphasizes 
            code readability with its notable use of significant indentation.`,
    },
    {
        id: 2,
        title: "JavaScript",
        content: `
            JavaScript, often abbreviated as JS, is a programming language that conforms to the 
            ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and 
            multi-paradigm.`,
    },
    {
        id: 3,
        title: "Go (Golang)",
        content: `
            Go, also known as Golang, is a statically typed, compiled programming language designed 
            at Google by Robert Griesemer, Rob Pike, and Ken Thompson. Go is syntactically similar 
            to C, but with memory safety, garbage collection, structural typing, and CSP-style 
            concurrency.,
    },
];

function VerticalTabs() {
    const [activeTab, setActiveTab] = useState(0);
    const [streamedContent, setStreamedContent] = useState("");

    useEffect(() => {
        // Split content into characters
        const characters = tabs[activeTab].content.split("");
        setStreamedContent("");

        let charIndex = 0;
        const interval = setInterval(() => {
            if (charIndex < characters.length) {
                setStreamedContent(
                    (prevContent) => `${prevContent}${characters[charIndex]}`
                );
                charIndex++;
            } else {
                clearInterval(interval);
            }
        }, 50); // Adjust this value to speed up or slow down the streaming effect

        return () => clearInterval(interval); // Clean up interval
    }, [activeTab]);

    return (
        <div className="flex">
            <div className="w-1/4">
                {tabs.map((tab, index) => (
                    <button
                        key={tab.id}
                        className={`block w-full text-left p-4 ${
                            activeTab === index
                                ? "bg-blue-500 text-white"
                                : "bg-gray-200"
                        }`}
                        onClick={() => setActiveTab(index)}
                    >
                        {tab.title}
                    </button>
                ))}
            </div>
            <div className="w-3/4 p-4 border border-gray-300">
                {streamedContent}
            </div>
        </div>
    );
}
export default VerticalTabs;

In App.js, bring in and utilize the VerticalTabs component:

import React from 'react';
import './App.css';
import VerticalTabs from './VerticalTabs';

function App() {
  return (
    <div className="App">
      <VerticalTabs />
    </div>
  );
}

export default App;

💁 Check out our other articles😃

 👉  Generate a free Developer Portfolio website with AI prompts

 👉  Mastering Button Customization in React with Tailwind CSS

TAGGED: accessibility, animations, design patterns, front-end development, interactivity, javascript, Performance Optimization, react, TailwindCSS, typewriter effect, UI/UX, web components, web design

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter Copy Link Print
Previous Article Remove Duplicate Words in Python Remove Duplicate Words in Python
Next Article The AI Revolution this week Must Read – The AI Revolution this week 30 Sep 2023: Integrating AI Tools into Everyday Life
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Twitter Follow
Telegram Follow

Subscribe Now

Subscribe to our newsletter to get our newest articles instantly!

Most Popular
Advanced Routing Techniques in Nextjs 15
Advanced Routing Techniques in Next js 15
20 November 2024
Attachment Details Image-to-Text-Converter-with-Claude-Nextjs-15
Building an AI-Powered Image-to-Text Converter with Claude, Next.js 15, and Vercel AI SDK
20 November 2024
Generate-Dynamic-OpenGraph-Images-in-Nextjs15
How to Generate Dynamic OpenGraph Images in Next.js App Router 15 with TypeScript
20 November 2024
Google Analytics 4 in Nextjs 14
How to Install Google Analytics 4 in Next.js 15 (App Router) with TypeScript [2024]
20 November 2024
docker compose
Getting Started with Docker Compose
20 November 2024

You Might Also Like

Advanced Routing Techniques in Nextjs 15
TutorialNextjs

Advanced Routing Techniques in Next js 15

7 Min Read
Attachment Details Image-to-Text-Converter-with-Claude-Nextjs-15
TutorialNextjs

Building an AI-Powered Image-to-Text Converter with Claude, Next.js 15, and Vercel AI SDK

4 Min Read
Generate-Dynamic-OpenGraph-Images-in-Nextjs15
TutorialNextjs

How to Generate Dynamic OpenGraph Images in Next.js App Router 15 with TypeScript

9 Min Read
Google Analytics 4 in Nextjs 14
TutorialNextjs

How to Install Google Analytics 4 in Next.js 15 (App Router) with TypeScript [2024]

6 Min Read

Always Stay Up to Date

Subscribe to our newsletter to get our newest articles instantly!

the geeky codes geeky code red logo

Providing valuable resources for developers in the form of code snippets, software tutorials, and AI related content.

About

  • About Us
  • Contact
  • Terms and Conditions
  • Privacy Policy
  • Disclaimer
  • Affiliate Disclosure

Resource

  • The Art of AI Prompt Engineering: Crafting Effective Inputs for AI Models

Get the Top 10 in Search!

Looking for a trustworthy service to optimize the company website?
Request a Quote
© 2023 The Geeky Codes. All Rights Reserved
We are happy to see you join Us!

🔥📢Subscribe to our newsletter and never miss our latest code snippets, tutorials and AI updates

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?