[React] 코딩 타자 연습 사이트 만들기 (2) - 정답 확인

Maple·2024년 10월 25일
0

코드보기 : https://github.com/maplesyrup0423/DevTyper

1. 기본 프론트 디자인

TypingArea.jsx

import React, { useState } from "react";
import "./TypingArea.css";

function TypingArea() {
  return (
    <div className="typing-area">
      <h2>타자 연습</h2>
      <div className="code-container">const hello = 'Hello, world!';</div>
      <textarea placeholder="코드를 따라 입력하세요" />
    </div>
  );
}

export default TypingArea;

코드의 경우 임시 하드코딩

TypingArea.css

body {
  background-color: black;
  color: white;
}
.typing-area {
  width: 600px;
  margin: auto;
  margin-top: 150px;
  border: 2px solid #4caf50;
  border-radius: 10px;
  padding: 20px;
}
h2 {
  text-align: center;
}
.code-container {
  margin-bottom: 10px;
  font-family: "Courier New", Courier, monospace;
  font-size: 25px;
  border: 1px solid #4caf50;
  color: lightgray;
  padding: 20px;
  border-radius: 8px;
  padding: 10px;
}
textarea {
  width: 600px;
  background-color: black;
  color: white;
  border: 1px solid #4caf50;
  font-size: 15px;
  border-radius: 8px;
  padding: 10px;
  box-sizing: border-box;
  resize: none;
  outline: none;
}

2. 타이핑 정답 확인 로직 추가

import React, { useState } from "react";
import "./TypingArea.css";

function TypingArea() {
  const [codeToType] = useState("const hello = 'Hello, world!';");
  const [userInput, setUserInput] = useState("");

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

  const renderCode = () => {
    return codeToType.split("").map((char, index) => {
      let color;
      let bgColor;
      if (index < userInput.length) {
        if (userInput[index] === char) {
          color = "green";
        } else {
          bgColor = "red"; // 틀린 글자 배경 빨간색
        }
      }
      return (
        <span
          key={index}
          style={{
            backgroundColor: bgColor,
            color: color,
          }}
        >
          {char}
        </span>
      );
    });
  };

  return (
    <div className="typing-area">
      <h2>타자 연습</h2>
      <div className="code-container">{renderCode()}</div>
      <textarea
        placeholder="코드를 따라 입력하세요"
        value={userInput}
        onChange={handleInputChange}
      />
    </div>
  );
}

export default TypingArea;


문제 코드와 사용자 입력이 일치할 경우 텍스트 색을 초록색으로
불일치할 경우 배경색을 빨간색으로 변경
사용자가 타이핑할 때마다 handleInputChange 을 호출하여 실시간으로 확인 가능

0개의 댓글