Front/React

React 카운터 앱 만들기 - component, useState

oodada 2024. 3. 4. 12:47
반응형

카운터 앱 만들기

  • 리액트를 이용한 숫자를 증가시키거나 감소시키는 앱을 만들어보자.

1. 프로젝트 생성

npx create-react-app counter-app
cd counter-app
npm start

2. 컴포넌트(Components) 생성

  • src 디렉토리에 Viewer.js 파일을 생성한다.
// src/Viewer.js
import React from 'react'

function Viewer() {
    return (
        <div>
            <h1>0</h1>
        </div>
    )
}

export default Viewer
  • src 디렉토리에 Counter.js 파일을 생성한다.
// src/Counter.js
import React from 'react'

function Counter() {
    return (
        <div>
            <button>+</button>
            <button>-</button>
        </div>
    )
}

export default Counter
  • src 디렉토리에 App.js 파일을 수정한다.
// src/App.js
import React from 'react'
import Counter from './Counter'
import Viewer from './Viewer'

function App() {
    return (
        <div>
            <Viewer />
            <Counter />
        </div>
    )
}

export default App

3. 상태(State) 관리

// src/App.js
import React, { useState } from 'react'
import Viewer from './component/counter/Viewer'
import Counter from './component/counter/Counter'

export default function App() {
    const [count, setCount] = useState(0)
    const handleSetCount = (value) => {
        setCount(count + value)
    }
    return (
        <>
            <Viewer count={count} />
            <Counter handleSetCount={handleSetCount} />
        </>
    )
}
// src/Viewer.js
import React from 'react'

// count를 props로 전달받음
function Viewer({ count }) {
    return (
        <div>
            <h1>{count}</h1>
        </div>
    )
}

export default Viewer
// src/Counter.js
const Counter = ({ handleSetCount }) => {
    // handleSetCount로 받음
    return (
        <div>
            <button onClick={() => handleSetCount(-1)}>-1</button>
            <button onClick={() => handleSetCount(-10)}>-10</button>
            <button onClick={() => handleSetCount(10)}>+10</button>
            <button onClick={() => handleSetCount(1)}>+1</button>
        </div>
    )
}

export default Counter
반응형
티스토리 친구하기