[리액트를 다루는 기술] TodoList filter를 이용해 삭제

쿼카쿼카·2022년 9월 8일
0

App.js

import React, { useCallback, useRef, useState } from 'react';
import TodoInsert from './components/TodoInsert';
import TodoList from './components/TodoList';
import TodoTemplate from './components/TodoTemplate';

function App() {
  const [todos, setTodos] = useState([
    {
      id: 1,
      text: '리액트의 기초 알아보기',
      checked: true,
    },
    {
      id: 2,
      text: '컴포넌트 스타일링 해보기',
      checked: true,
    },
    {
      id: 3,
      text: '일정 관리 앱 만들기',
      checked: false,
    },
  ]);

  // 고윳값으로 사용될 id
  // ref를 사용하여 변수 담기
  const nextId = useRef(4);

  // props로 전달되는 함수는 useCallback으로 전달
  const onInsert = useCallback(text => {
    const todo = {
      id: nextId.current,
      text,
      checked: false,
    };
    setTodos(todos.concat(todo));
    nextId.current++;
  }, [todos]);

  // remove 함수
  const onRemove = useCallback(id => {
    setTodos(todos.filter(todo => todo.id !== id))
  }, [todos]);

  return (
    <>
      <TodoTemplate>
        <TodoInsert onInsert={onInsert} />
        <TodoList todos={todos} onRemove={onRemove} />
      </TodoTemplate>
    </>
  );
}

export default App;

TodoList.js

import './TodoList.scss';
import TodoListItem from './TodoListItem';

function TodoList({todos, onRemove}) {
  return (
    <div className='TodoList'>
      {todos.map(todo => (
        // onRemove 넘겨주기
        <TodoListItem todo={todo} key={todo.id} onRemove={onRemove} />
      ))}
    </div>
  )
}

export default TodoList;

TodoListItem.js

import {
  MdCheckBoxOutlineBlank,
  MdRemoveCircleOutline,
  MdCheckBox
} from 'react-icons/md';
import cn from 'classnames';
import './TodoListItem.scss';

function TodoListItem({todo, onRemove}) {
  // id 추가
  const {id, text, checked} = todo;
  return (
    <div className='TodoListItem'>
      <div className={cn('checkbox', {checked})}>
        {checked ? <MdCheckBox /> : <MdCheckBoxOutlineBlank />}
        <div className='text'>{text}</div>
      </div>
      {/* 매개변수 있을 땐 콜백함수로 onRemove 사용 */}
      <div className="remove" onClick={() => onRemove(id)}>
        <MdRemoveCircleOutline />
      </div>
    </div>
  )
}

export default TodoListItem

매개변수가 있는 함수

  • onClick={() => onRemove(id)}에서 onRemove 매개변수 여부에 따라
    • onClick={onRemove}: 매개변수 없을 때
    • onClick={() => onRemove(매개변수)}: 매개변수 있을 때
profile
쿼카에요

0개의 댓글