const onEdit = (targetId, newContent) => {
setData(
data.map((it) => (it.id === targetId ? {...it, content: newContent} : it))
);
};
data의 map이라는 내장 함수를 사용해서 바꾸려는 댓글 아이디값이 일치하면 콘텐트만 뉴 콘텐츠로 수정하고 댓글 아이디값이 일치 안하면 기존 데이터를 뿌린다. 위 코드를 app에서 만들고 props로 아래 코드까지 전달한다.
import {useRef, useState} from "react";
const DiaryItem = ({
onEdit,
onRemove,
author,
content,
created_date,
emotion,
id,
}) => {
const [isEdit, setIsEdit] = useState(false);
const toggleIsEdit = () => setIsEdit(!isEdit);
const [localContent, setLocalContent] = useState(content);
const localContentInput = useRef();
const handleRemove = () => {
console.log(id);
if (window.confirm(`${id}번째를 정말 삭제하시겠습니까?`)) {
onRemove(id);
}
};
const handleQuitEdit = () => {
setIsEdit(false);
setLocalContent(content);
};
const handleEdit = () => {
if (localContent.length < 5) {
localContentInput.current.focus();
return;
}
if (window.confirm(`${id} 번째 일기를 수정하겠습니까?`))
onEdit(id, localContent);
toggleIsEdit();
};
return (
<div className="DiaryItem">
<div className="info">
<span>
작성자 : {author} | 감정점수 : {emotion}
</span>
<br />
<span className="date">
{new Date(created_date).toLocaleDateString()}
</span>
</div>
<div className="content">
{isEdit ? (
<>
<textarea
ref={localContentInput}
value={localContent}
onChange={(e) => setLocalContent(e.target.value)}
/>
</>
) : (
<>{content}</>
)}
</div>
{isEdit ? (
<>
<button onClick={handleQuitEdit}>수정취소</button>
<button onClick={handleEdit}>수정완료</button>
</>
) : (
<>
<button onClick={handleRemove}>삭제하기</button>
<button onClick={toggleIsEdit}>수정하기</button>
</>
)}
</div>
);
};
export default DiaryItem;
handleEdit에 onEdit 코드를 넣어 아이디와 수정 댓글 내용을 전달한다.