How Can I Fix the Loop Typewriter Effect in My React Component to Correctly Cycle Through Words Without Errors?

Recently, while working on a project that required a typewriter effect for text animations within a React application, I encountered a few issues. The goal was to cycle through an array of words (“Business”, “Company”, “Startup”), displaying them one after the other in a loop. However, upon implementation, I noticed that after completing the initial cycle through the array, the first word wasn’t being typed again. There were also unexpected ‘undefined’ entries appearing at the end of the cycle before starting over, which was not the intended behavior.

Here’s a look at the code that presented these issues:

const words = ["Business", "Company", "Startup"];

let i = 0;
let a = 0;
let txt = `${words[a]}`;
let speed = 1100;
let loop = true;

function Home() {
  const typeWriter = (headerMessage) => {
    if (i < txt.length) {
      headerMessage.innerHTML += txt.charAt(i);
      i++;
      setTimeout(() => typeWriter(headerMessage), speed);
    } else if (loop) {
      clearText(headerMessage);
    }
  }

  const clearText = (headerMessage) => {
    headerMessage.innerHTML = "";
    i = 0;
    a++;
    txt = `${words[a]}`;
    if (a > 3) {
      a = 0;
    }
    setTimeout(() => {
      typeWriter(headerMessage);
    }, 2000);
  }

  useEffect(() => {
    const headerMessage = document.getElementById("header-message");
    if (headerMessage) {
      typeWriter(headerMessage);
    }
  }, []);
  
  return (
    <main>
      <section>
        <section>
          <div>Let Us Help Grow Your<p id="header-message"></p>.</div>
        </section>
        <section></section>
      </section>
    </main>
  );
}

Upon reviewing the code, I noticed a couple of key points that needed addressing to correct the typewriter effect:

  1. Array Indexing Error: The condition in the clearText function’s if statement checked if index a was greater than 3, which is incorrect since array indices go from 0 to 2 for a 3-element array.
  1. Handling the Looping: The typewriter function should handle the cyclic repetition of words smoothly without jumping to ‘undefined’.

Here’s an improved version of the code that addresses these issues:

const words = ["Business", "Company", "Startup"];

let i = 0;
let a = 0;
let txt = words[a];  // Cleaner initialization
let speed = 1100;
let loop = true;

function Home() {
  const typeWriter = (headerMessage) => {
    if (i < txt.length) {
      headerMessage.innerHTML += txt.charAt(i);
      i++;
      setTimeout(() => typeWriter(headerMessage), speed);
    } else if (loop) {
      clearText(headerMessage);
    }
  }

  const clearText = (headerMessage) => {
    headerMessage.innerHTML = "";
    i = 0;
    a = (a + 1) % words.length;  // Use modulo to wrap array index automatically
    txt = words[a];
    setTimeout(() => {
      typeWriter(headerMessage);
    }, 2000);
  }

  useEffect(() => {
    const headerMessage = document.getElementById("header-message");
    if (headerMessage) {
      typeWriter(headerMessage);
    }
  }, []);
  
  return (
    <main>
      <section>
        <section>
          <div>Let Us Help Grow Your<p id="header-message"></p>.</div>
        </section>
        <section></section>
      </section>
    </main>
  );
}

In the revised clearText function, I used the modulo operator (a + 1) % words.length to ensure the index wraps around to 0 after reaching the end of the array. This prevents any undefined indices and ensures that the list of words cycles correctly.

This modification ensures seamless transitions between the words and guarantees that each word in the array is displayed accurately without errors like ‘undefined’ appearing. This improved loop makes the effect cleaner and preserves the user’s desired functionality. As I integrated these adjustments and retested the component, the typewriter effect functioned flawlessly, cycling through each word repeatedly as expected.


Comments

Leave a Reply

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