본문 바로가기

React.js

리스트 데이터 삭제하기

각각의 아이템들에 '삭제' 버튼을 생성

삭제하기 버튼을 누르면, 이전처럼 App 컴포넌트가 가지고 있는 data의 State를 바꿔줘야 한다. 

onDelete() 생성

배열 요소의 Id를 onDelete함수에 전달할 수 있어야 하며, DiaryItem이 onDelete()함수를 호출할 수 있어야 한다. 

DiaryItem의 부모인 DiaryList props로 onDelete 함수를 내려준 다음에, DiaryList에서는 부모로부터 
onDelete props를 받아서 내려줘야 한다. 

 

<DiaryEditor.js>

import React, {useRef, useState } from "react";


const DiaryEditor = ({onCreate}) => { // onCreat 함수를 Props으로 전달 받음

    const authorInput = useRef();
    const contentInput =useRef();

    const [state, setState] = useState({
        author:"",
        content:"",
        emotion:1,  
    });

    const handleChangeDiary = (e) => {
        setState({
            ...state,
            [e.target.name] : e.target.value,
        });
    };
    
    const handleSubmit = () => {
        if(state.author.length < 1){
            authorInput.current.focus();
            return;
        }

        if(state.content.length < 5) {
            contentInput.current.focus();
            return;
        }
        // Props로 받은 onCreate 호출
        onCreate(state.author, state.content, state.emotion);  
        alert('저장 성공');
        // 성공하면 데이터 초기화 수행
        setState({
            author : "", 
            content : "", 
            emotion : 1,
        });
    };

    return (
        <div className = "DiaryEditor">
        <h2> 오늘의 일기 </h2>
        <div>
            <input 
            ref = {authorInput}
            name = "author"
            type="text"
            value={state.author} 
            onChange={handleChangeDiary}
            />
        </div>
        <div>
            <textarea 
            ref = {contentInput}
            name = "content"
            type = "text"
            value = {state.content}
            onChange={handleChangeDiary}
        /></div>
        <div>
            <span>오늘의 감정점수 : </span>
            <select name = "emotion" 
            value={state.emotion} 
            onChange={handleChangeDiary}>
                <option value={1}>1</option>
                <option value={2}>2</option>
                <option value={3}>3</option>
                <option value={4}>4</option>
                <option value={5}>5</option>
            </select>
        </div>
        <div>
            <button onClick = {handleSubmit}>일기 저장하기</button>
        </div>
    </div>
    );
};
export default DiaryEditor;

<DiaryList.js>

import DiaryItem from './DiaryItem';


const DiaryList = ({onRemove, diaryList}) => {
    return (
    <div className = "DiaryList">
    <h2>일기 리스트</h2>
    <h4>{diaryList.length}개의 일기가 있습니다.</h4>
    <div>
        {diaryList.map((it) => (
            <DiaryItem key = {it.id} {...it} onRemove={onRemove} /> // 이런식으로 내려줌
            ))}
        </div>
    </div>
    );
};

DiaryList.defaultProps = { 
    diaryList:[], 
};

export default DiaryList;

<DiaryItem.js>

const DiaryItem = ({
    onDelete, // 함수를 Props로 받는다. 
    id,
    author, 
    content, 
    emotion, 
    created_date, 
}) => {
    return( 
    <div className = "DiaryItem">
    <div className = "info">
        <span className = "author_info">
            작성자 : {author} | 감정 : {emotion}
        </span>
        <br />
        <span className = "date">
            {new Date(created_date).toLocaleString()}
            </span> 
    </div>
    <div className="content">{content}</div>
    <button 
    onClick={() => {
        console.log(id); 
        // 삭제 여부 알림
        if(window.confirm(`${id}번째 일기를 정말 삭제하시겠습니까?`)){
            onDelete(id); // onDelete의 현재 id를 전달
        }
    }}
    >
        삭제하기
        </button>
    </div>
    );
};

export default DiaryItem;

<App.js>

import {useRef, useState} from "react"; 
import './App.css';
import DiaryEditor from './DiaryEditor';
import DiaryList from './DiaryList';




function App() {

  const [data, setData] = useState([]); // 일기 데이터 배열 저장

const dataId = useRef(0)

  const onCreate = (author, content, emotion) => {
    const created_date = new Date().getTime(); 
    const newItem = { 
      author,
      content,
      emotion,
      created_date, 
      id : dataId.current
    };
    dataId.current += 1;
    setData([newItem,...data])// 원래 배열에 있던 data를 하나씩 나열(...data) 
  };

  const onRemove = (targetId) => {
    console.log(`${targetId}가 삭제되었습니다.`);
    const newDiaryList = data.filter((it) => it.id !== targetId); // 
    setData(newDiaryList); // 이렇게 전달해주면 삭제 된다.
  };


  return ( // State는 DiaryList로 사용되기 때문에, Props로 data 내려준다.
    <div className="App">
      <DiaryEditor onCreate ={onCreate} />
            <DiaryList onRemove={onRemove} diaryList = {data}/> 
    </div>
  );
}

export default App;