본문 바로가기
React

[React] Tailwind CSS와 useState를 활용한 간단한 계산기 구현

by teamnova 2025. 7. 24.
728x90

 

안녕하세요 오늘은 React의 useState 훅과 Tailwind CSS를 활용하여

간단한 계산기를 만들어 보는 예제를 함께 살펴보겠습니다.

계산기 예제는 매우 간단하지만 프론트엔드 개발의 핵심인 상태 관리, 이벤트 처리, 그리고 UI 구성을 매우 효과적으로 배우고 이해할 수 있는 좋은 예제입니다.

( React 프로젝트 환경: vite )

 

 

1.  상태 관리 및 로직 

- 계산기의 핵심 기능과 내부 데이터를 관리합니다. 

- useState 훅: React에서 컴포넌트의 상태(데이터)를 관리하기 위해 사용하는 훅입니다.

- handleNumber(num) 함수: 숫자 버튼(0-9, .)이 클릭되었을 때 호출됩니다.

- handleOperator(op) 함수: 연산자 버튼(+, -, *, /)이 클릭되었을 때 호출됩니다.

- handleEqual() 함수: = 버튼이 클릭되었을 때 호출됩니다. 

import React, { useState } from 'react'

function SimpleCalculator() {
  const [display, setDisplay] = useState('0')
  const [equation, setEquation] = useState('')

  const handleNumber = (num) => {
    const numStr = String(num); // 입력된 숫자를 문자열로 변환

    if (display === '0') { // 현재 화면이 '0'일 경우 (초기 상태 또는 연산자 입력 후)
      setDisplay(numStr) // '0'을 새로운 숫자로 교체
    } else { // '0'이 아닌 다른 숫자가 있을 경우
      setDisplay(display + numStr) // 새로운 숫자를 기존 숫자 뒤에 이어 붙임
    }
  }

  const handleOperator = (op) => { // 연산자 버튼 (+, -, *, /) 클릭 시
    setEquation(display + ' ' + op + ' ') // 현재 화면의 숫자와 연산자를 수식에 추가
    setDisplay('0') // 화면을 '0'으로 초기화하여 다음 숫자 입력을 준비
  }

  const handleEqual = () => { // '=' 버튼 클릭 시
    const result = eval(equation + display) // 현재 수식과 화면의 숫자를 합쳐 eval()로 계산
    setDisplay(result.toString()) // 계산 결과를 화면에 표시 (문자열로 변환)
    setEquation('') // 수식 초기화
  }

  const handleClear = () => { // 'AC' (All Clear) 버튼 클릭 시
    setDisplay('0') // 화면을 '0'으로 초기화
    setEquation('') // 수식을 초기화
  }
}

 

 

2. UI 렌더링

- 계산기의 시각적인 구조를 정의하고, Tailwind CSS를 이용해 스타일을 입히며, 위에서 정의한 로직 함수들을 각 버튼에 연결합니다.

return (
    <div className="max-w-sm mx-auto py-20 bg-gray-100">
      <h2 className="text-3xl font-bold text-center mb-8">간단한 계산기</h2>
      
      <div className="bg-white p-6 rounded-lg shadow-lg">
        {/* Display */}
        <div className="mb-4">
          <div className="text-right text-gray-500 text-sm h-6">{equation}</div>
          <div className="text-right text-3xl font-bold bg-gray-50 p-4 rounded">
            {display}
          </div>
        </div>

        {/* Buttons */}
        <div className="grid grid-cols-4 gap-2">
          <button onClick={handleClear} className="col-span-2 p-4 bg-red-500 text-white rounded hover:bg-red-600">
            AC
          </button>
          <button onClick={() => handleOperator('/')} className="p-4 bg-gray-300 rounded hover:bg-gray-400">
            ÷
          </button>
          <button onClick={() => handleOperator('*')} className="p-4 bg-gray-300 rounded hover:bg-gray-400">
            ×
          </button>

          {[7, 8, 9].map(num => (
            <button key={num} onClick={() => handleNumber(num)} className="p-4 bg-gray-200 rounded hover:bg-gray-300">
              {num}
            </button>
          ))}
          <button onClick={() => handleOperator('-')} className="p-4 bg-gray-300 rounded hover:bg-gray-400">
            -
          </button>

          {[4, 5, 6].map(num => (
            <button key={num} onClick={() => handleNumber(num)} className="p-4 bg-gray-200 rounded hover:bg-gray-300">
              {num}
            </button>
          ))}
          <button onClick={() => handleOperator('+')} className="p-4 bg-gray-300 rounded hover:bg-gray-400">
            +
          </button>

          {[1, 2, 3].map(num => (
            <button key={num} onClick={() => handleNumber(num)} className="p-4 bg-gray-200 rounded hover:bg-gray-300">
              {num}
            </button>
          ))}
          <button onClick={handleEqual} className="row-span-2 p-4 bg-blue-500 text-white rounded hover:bg-blue-600">
            =
          </button>

          <button onClick={() => handleNumber('0')} className="col-span-2 p-4 bg-gray-200 rounded hover:bg-gray-300">
            0
          </button>
          <button onClick={() => handleNumber('.')} className="p-4 bg-gray-200 rounded hover:bg-gray-300">
            .
          </button>
        </div>
      </div>
    </div>
  )
}

export default SimpleCalculator

 

 

 

전체 코드 입니다. 

import React, { useState } from 'react'

function SimpleCalculator() {
  const [display, setDisplay] = useState('0')
  const [equation, setEquation] = useState('')

  const handleNumber = (num) => {

     const numStr = String(num);
    if (display === '0') {
      setDisplay(numStr)
    } else {
      setDisplay(display + numStr)
    }
  }

  const handleOperator = (op) => {
    setEquation(display + ' ' + op + ' ')
    setDisplay('0')
  }

  const handleEqual = () => {
    const result = eval(equation + display)
    setDisplay(result.toString())
    setEquation('')
  }

  const handleClear = () => {
    setDisplay('0')
    setEquation('')
  }

  return (
    <div className="max-w-sm mx-auto py-20 bg-gray-100">
      <h2 className="text-3xl font-bold text-center mb-8">간단한 계산기</h2>
      
      <div className="bg-white p-6 rounded-lg shadow-lg">
        {/* Display */}
        <div className="mb-4">
          <div className="text-right text-gray-500 text-sm h-6">{equation}</div>
          <div className="text-right text-3xl font-bold bg-gray-50 p-4 rounded">
            {display}
          </div>
        </div>

        {/* Buttons */}
        <div className="grid grid-cols-4 gap-2">
          <button onClick={handleClear} className="col-span-2 p-4 bg-red-500 text-white rounded hover:bg-red-600">
            AC
          </button>
          <button onClick={() => handleOperator('/')} className="p-4 bg-gray-300 rounded hover:bg-gray-400">
            ÷
          </button>
          <button onClick={() => handleOperator('*')} className="p-4 bg-gray-300 rounded hover:bg-gray-400">
            ×
          </button>

          {[7, 8, 9].map(num => (
            <button key={num} onClick={() => handleNumber(num)} className="p-4 bg-gray-200 rounded hover:bg-gray-300">
              {num}
            </button>
          ))}
          <button onClick={() => handleOperator('-')} className="p-4 bg-gray-300 rounded hover:bg-gray-400">
            -
          </button>

          {[4, 5, 6].map(num => (
            <button key={num} onClick={() => handleNumber(num)} className="p-4 bg-gray-200 rounded hover:bg-gray-300">
              {num}
            </button>
          ))}
          <button onClick={() => handleOperator('+')} className="p-4 bg-gray-300 rounded hover:bg-gray-400">
            +
          </button>

          {[1, 2, 3].map(num => (
            <button key={num} onClick={() => handleNumber(num)} className="p-4 bg-gray-200 rounded hover:bg-gray-300">
              {num}
            </button>
          ))}
          <button onClick={handleEqual} className="row-span-2 p-4 bg-blue-500 text-white rounded hover:bg-blue-600">
            =
          </button>

          <button onClick={() => handleNumber('0')} className="col-span-2 p-4 bg-gray-200 rounded hover:bg-gray-300">
            0
          </button>
          <button onClick={() => handleNumber('.')} className="p-4 bg-gray-200 rounded hover:bg-gray-300">
            .
          </button>
        </div>
      </div>
    </div>
  )
}

export default SimpleCalculator

 

 

 

시연 영상입니다