React - Typewriter effect in the loop item

0 votes
121 views
added Mar 19 in React by lcjr First Warrant Officer (11,970 points)
import React, { useState, useRef, useEffect } from 'react';

const Typewriter = ({ text }) => {
  const [displayText, setDisplayText] = useState('');
  const [currentIndex, setCurrentIndex] = useState(0);
  const typingSpeed = 10; // Adjust typing speed as needed

  useEffect(() => {
    const interval = setInterval(() => {
      if (currentIndex <= text.length) {
        setDisplayText(text.substring(0, currentIndex));
        setCurrentIndex((prevIndex) => prevIndex + 1);
      } else {
        clearInterval(interval);
      }
    }, typingSpeed);

    return () => clearInterval(interval);
  }, [currentIndex, text]);

  return <span>{displayText}</span>;
};

const MyComp = () => {
  const [inputValue, setInputValue] = useState('');
  const [responseData, setResponseData] = useState(null);
  const [searchHistory, setSearchHistory] = useState([]);
  const lastItemRef = useRef(null);

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };

  const fetchData = async () => {
    try {
      const data = JSON.stringify({
        input: {
          message: inputValue,
        },
      });

      const response = await fetch(YOUR_API, {
        method: 'POST',
        body: data,
      });

      const responseData = await response.json();
      setResponseData(responseData);

      setSearchHistory((prevSearchHistory) => [
        ...prevSearchHistory,
        { question: inputValue, answer: responseData.output.response.content },
      ]);
    } catch (error) {
      console.error('Error:', error);
    }
  };

  const handleButtonClick = () => {
    fetchData();
  };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={handleInputChange}
        placeholder="Enter your message..."
      />
      <button type="button" onClick={handleButtonClick}>
        Send
      </button>

      <div>
        <h2>Search History:</h2>
        {searchHistory.map((item, index) => (
          <div
            key={index}
            className="buddy_qa_item"
            ref={index === searchHistory.length - 1 ? lastItemRef : null}
          >
            <div className="question">{item.question}</div>
            <div className="answer">
              <Typewriter text={item.answer} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default MyComp;

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...