본문 바로가기

FRONT/REACT.js

[REACT] React + TypeScript 사용해서 Todo 만들기

반응형

싸피에서 공통 프로젝트를 들어가게 되었다.
이번에는 욕심부리지 않고, 프론트로 최대한 노력해보려 한다.

 

12월에 React를 보긴 했는데, 거의 놀았다 ㅠㅠ

그래서 강의를 보고도 진행 과정만 알 뿐, 혼자 무엇인가 만들 능력이  되지 않았다. 

부끄럽다.

 

이번주에는 9~6시에 간단한 과제를 진행했는데, 리액트도 익숙치 않은데 타입스크립트, Jotai까지 한번에 쓰려고 하니까 머리가 터져버릴 것만 같았다. ㅠㅠ 하나로 만들어서 세분화해서 나눠야 한다는 것을 다다음날에야 알았다. 한번에 모든 타입과 구조를 컴포넌트화 하려고 하니, 내가 뭘 하는지도 잘 모르겠었다.

 

아무튼,  이제 다시 하나를 만들고 자주 사용하는 부분을 컴포넌트화 하고, 조타이를 씌워보자.

 

$ npx create-react-app 프로젝트명 --template typescript

 

위 코드를 bash에 적으면 typescript를 사용한 react 앱이 만들어진다.

 

 

TodoPage.tsx라는 파일을 pages 폴더 안에 만들었다.

 

function TodoPage() {
    return (
        <div>
            <h1>Todo List</h1>
            <input type="text"/>
            <button >
                Add
            </button>

        </div>
    )
}

export default TodoPage

 

처음에는 위 코드처럼 눈에 보일 것을 만들고, 입력할 데이터를 담을 곳이나 값의 상태변화를 인식할 useState를 사용하면 된다.

 

import {useState} from "react";
import {Todo} from "../type/Todo"

function TodoPage() {
    const [inputValue, setInputValue] = useState('')
    const [todoList, setTodoList] = useState<Todo[]>([])

    function onChangeValue(e: any) {
        setInputValue(e.target.value)
    }

    function addItem() {
        if (inputValue.trim() !== "") {
            const newTodo: Todo = {
                id: todoList.length + 1,
                text: inputValue,
            }
            setTodoList([...todoList, newTodo])
            setInputValue('')
        }
    }

    return (
        <div>
            <h1>Todo List</h1>
            <input value={inputValue} type="text" onChange={onChangeValue}/>
            <button onClick={addItem}>
                Add
            </button>

            <div>
                {todoList.map((todo) => (
                    <div key={todo.id}>
                        {todo.text}
                    </div>
                ))}
            </div>
        </div>
    )
}

export default TodoPage

 

이런 방식으로 코드를 짜면 된다. 

 

삭제버튼을 만들기 위해선 버튼에 key값을 주고, onClick에서 함수를 실행하도록 하면된다.

 

    function deleteItem(id: number) {
        const updateTodoList = todoList.filter((todo) => todo.id !== id)
        setTodoList(updateTodoList)
    }


    <div>
        {todoList.map((todo) => (
            <div key={todo.id}>
                {todo.text}
                <button onClick={() => deleteItem(todo.id)} key={todo.id}>
                    Del
                </button>
            </div>

        ))}
    </div>

 

위 코드를 추가하면 입력, 삭제가 가능한 TodoList가 완성된다.

 

전체 코드도 올리겠다.

 

import {useState} from "react";

export type Todo = {
    id: number
    text: string
}


function TodoPage() {
    const [inputValue, setInputValue] = useState('')
    const [todoList, setTodoList] = useState<Todo[]>([])

    function onChangeValue(e: any) {
        setInputValue(e.target.value)
    }

    function addItem() {
        if (inputValue.trim() !== "") {
            const newTodo: Todo = {
                id: todoList.length + 1,
                text: inputValue,
            }
            setTodoList([...todoList, newTodo])
            setInputValue('')
        }
    }

    function deleteItem(id: number) {
        const updateTodoList = todoList.filter((todo) => todo.id !== id)
        setTodoList(updateTodoList)
    }

    return (
        <div>
            <h1>Todo List</h1>
            <input value={inputValue} type="text" onChange={onChangeValue}/>
            <button onClick={addItem}>
                Add
            </button>

            <div>
                {todoList.map((todo) => (
                    <div key={todo.id}>
                        {todo.text}
                        <button onClick={() => deleteItem(todo.id)} key={todo.id}>
                            Del
                        </button>
                    </div>

                ))}
            </div>
        </div>
    )
}

export default TodoPage

 

반응형

'FRONT > REACT.js' 카테고리의 다른 글

[REACT] map 함수 사용하는데 마주친 에러  (0) 2024.01.06
[REACT] 새 프로젝트 생성하기  (0) 2024.01.02