react 텍스트 타이핑 효과 만들기

G-NOTE·2023년 8월 28일
0

React

목록 보기
27/27
import React, { useEffect, useState } from "react";
import AppLayout from "../components/layout/AppLayout";
import styled from "styled-components";

const FULL_SENTENCE =
  "당신의 디깅디스크를 만들어 드리는 MDD에 오신 것을 환영합니다.";

const RetroTyping = () => {
  const [sentence1, setSentence1] = useState<string>("");
  const [sentence2, setSentence2] = useState<string>("");
  const [sentence3, setSentence3] = useState<string>("");
  const [count, setCount] = useState<number>(0);
  const [blink, setBlink] = useState<number>(0);

  useEffect(() => {
    setTimeout(() => {
      if (count < 10) {
        setSentence1(sentence1 + FULL_SENTENCE[count]);
        setCount(count + 1);
      } else if (count < 30) {
        setBlink(1);
        setSentence2(sentence2 + FULL_SENTENCE[count]);
        setCount(count + 1);
      } else if (count < 36) {
        setBlink(2);
        setSentence3(sentence3 + FULL_SENTENCE[count]);
        setCount(count + 1);
      }
    }, 60);

    if (count > 34 && count < 44) {
      setTimeout(() => {
        setBlink((prev) => (prev === 2 ? 3 : 2));
        setCount(count + 1);
      }, 500);
    }
  }, [count]);

  console.log(count);

  return (
    <AppLayout>
      <h1>RetroTyping</h1>
      <StSentenceContainer>
        <StSentence>
          <span>{sentence1}</span>
          <StCursorContainer>
            {blink === 0 ? <StCursor></StCursor> : <></>}
          </StCursorContainer>
        </StSentence>
        <StSentence>
          <span>{sentence2}</span>
          <StCursorContainer>
            {blink === 1 ? <StCursor></StCursor> : <></>}
          </StCursorContainer>
        </StSentence>
        <StSentence>
          <span>{sentence3}</span>
          <StCursorContainer>
            {blink === 2 ? <StCursor></StCursor> : <></>}
          </StCursorContainer>
        </StSentence>
      </StSentenceContainer>
    </AppLayout>
  );
};

export default RetroTyping;

const StSentenceContainer = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #add8e6;
  width: 400px;
  height: 300px;
  margin: auto;
`;

const StSentence = styled.div`
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 1px;

  span {
    line-height: 24px;
    font-size: 16px;
  }
`;

const StCursorContainer = styled.div`
  width: 2px;
  height: 16px;
  display: flex;
  align-items: center;
`;

const StCursor = styled.div`
  width: 2px;
  height: 16px;
  background-color: #000000;
`;

줄바꿈이 들어가야 해서 코드가 좀 길어진 듯..

완성 화면

retro_typing

profile
FE Developer

0개의 댓글