PROGRAMING/React

[REACT] Simple calculator - useReducer

donghunl 2024. 3. 7. 04:59
반응형

Build a simple calculator.

 

useReducer: Sometimes state becomes complicated in React, and there are multiple mutations you will need to implement on your data. useReducer helps simplify this by moving state management outside of the component.

 

Implement the logic so that two numbers can be selected.

Implement the logic to add these two selected numbers together. Same for subtraction

Implement a clear function that will reset both numbers to 0.

Use useReducer to store and modify your data.

 

SimpleCalculator.js

import { useReducer } from "react"

const initialState = {
  num1: 0,
  num2: 0,
  result: 'no result yet'
}

function reducer(state, action) {
  if (action.type === 'SET_NUM_ONE') return { ...state, num1: action.number }
  if (action.type === 'SET_NUM_TWO') return { ...state, num2: action.number }
  if (action.type === 'ADD') return { ...state, result: state.num1 + state.num2 }
  if (action.type === 'SUBTRACT') return { ...state, result: state.num1 - state.num2 }
  if (action.type === 'CLEAR') return initialState
}

export default function SimpleCalculator() {
  const [state, dispatch] = useReducer(reducer, initialState)
  const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  return (
    <div>
      <div>
        <h2>Number 1</h2>
        {numbers.map(number => (
          <button key={number} onClick={() => dispatch({ type: 'SET_NUM_ONE', number })}>
            {number}
          </button>))}
      </div>
      <div>
        <h2>Number 2</h2>
        {numbers.map(number => (
          <button key={number} onClick={() => dispatch({ type: 'SET_NUM_TWO', number })}>
            {number}
          </button>))}
      </div>
      <div>
        <h2>Actions</h2>
        <button onClick={() => dispatch({ type: 'ADD' })}>+</button>
        <button onClick={() => dispatch({ type: 'SUBTRACT' })}>-</button>
        <button onClick={() => dispatch({ type: 'CLEAR' })}>c</button>
      </div>
      <div><h2>Result:{state.result}</h2></div>
    </div>
  )
}

 

App.js

import SimpleCalculator from './SimpleCalculator'

function App () {
  return (
    <div className='App'>
      <SimpleCalculator/>
    </div>
  )
}

export default App

 

결과 화면

반응형

'PROGRAMING > React' 카테고리의 다른 글

[REACT] Simple shopping cart  (1) 2024.03.07
[REACT] Focus an input - useRef  (1) 2024.03.07
[REACT] Pixel art - React Context  (0) 2024.03.07
[REACT] Color picker  (0) 2024.03.07
[REACT] Window event  (0) 2024.03.07