Ответы пользователя по тегу React
  • Как сделать анимацию появления текста по букве в реакте?

    @rjyk
    let text = 'qwertyu';
    let output = '';
    let currentIndex = 0;
    
    let intervalID = setInterval(() => {
        output += text[currentIndex];
        currentIndex += 1;
        console.log(output);
        if (currentIndex === text.length) {
            clearInterval(intervalID)
        };
    }, 1000)


    Также рекомендуют это делать через useEffect хук:
    function RenderSubtitle() {
      const [subtitle, setSubtitle] = useState('');
      const text = 'qwertyu';
      let currentIndex = 0;
    
      useEffect(() => {
        const id = setInterval(() => {
          setSubtitle(prev => prev + text[currentIndex] );
          currentIndex += 1;
          if (currentIndex === text.length) {
              clearInterval(id)
          };
        }, 1000);
        return () => clearInterval(id);
      }, []);
    
      return <h1>{subtitle}</h1>;
    }
    Ответ написан
    Комментировать