다뤄야 할 내용
- PostContext에 deletePost() 함수 추가
- 글 상세 페이지(PostPage)에서 삭제 버튼 구현
- 삭제 후 홈(/)으로 이동
PostContext 수정
deletePost 추가
import { createContext, useState, useEffect } from "react";
export const PostContext = createContext();
export function PostProvider({ children }) {
const [posts, setPosts] = useState(() => {
const saved = localStorage.getItem("posts");
return saved ? JSON.parse(saved) : [];
});
useEffect(() => {
localStorage.setItem("posts", JSON.stringify(posts));
}, [posts]);
const addPost = (title, content) => {
const newPost = {
id: Date.now(),
title,
content,
};
setPosts([newPost, ...posts]);
};
const updatePost = (id, title, content) => {
setPosts(posts.map((p) => (p.id === id ? { ...p, title, content } : p)));
};
const deletePost = id => {
const ok = window.confirm('정말 삭제하시겠습니까?');
if (ok) {
setPosts(posts.filter(p => p.id !== id));
}
};
return (
<PostContext.Provider value={{ posts, addPost, updatePost, deletePost }}>
{children}
</PostContext.Provider>
);
}
핵심1
const deletePost = id => {
const ok = window.confirm('정말 삭제하시겠습니까?');
if (ok) {
setPosts(posts.filter(p => p.id !== id));
}
};
핵심 2
<PostContext.Provider value={{ posts, addPost, updatePost, deletePost }}>
{children}
</PostContext.Provider>
-> deletePost 추가
PostPage에서 삭제 버튼 추가
PostPage.jsx 수정
import { useContext, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { PostContext } from "../context/PostContext";
import PostForm from "../components/PostForm";
function PostPage() {
const { posts, updatePost, deletePost } = useContext(PostContext);
const { id } = useParams();
const post = posts.find((p) => p.id === Number(id));
const navigate = useNavigate();
const [editing, setEditing] = useState(false);
// 댓글 관련
const [comments, setComments] = useState([]);
const [commentText, setCommentText] = useState("");
const handleCommentSubmit = (e) => {
e.preventDefault();
if (!commentText.trim()) return;
const newComment = { id: Date.now(), text: commentText };
setComments([...comments, newComment]);
setCommentText("");
};
if (!post) return <p>글을 찾을 수 없습니다.</p>;
return (
<div>
{editing ? (
<PostForm
initialTitle={post.title}
initialContent={post.content}
submitLabel="수정"
onSubmit={(title, content) => {
updatePost(post.id, title, content);
setEditing(false);
}}
/>
) : (
<>
<h2 className="text-2xl font-bold mb-2">{post.title}</h2>
<p className="mb-4 text-gray-700">{post.content}</p>
<button className="bg-blue-500 text-white p-2 rounded-md mr-2" onClick={() => setEditing(true)}>수정하기</button>
<button className="bg-red-500 text-white p-2 rounded-md" onClick={() => deletePost(post.id)}>삭제</button>
</>
)}
<hr />
<h3>댓글</h3>
<form onSubmit={handleCommentSubmit}>
<input className="border border-gray-300 p-2 mb-2 w-full"
type="text"
placeholder="댓글을 입력하세요"
value={commentText}
onChange={(e) => setCommentText(e.target.value)}
/>
<button className="bg-blue-500 text-white p-2 rounded-md" type="submit">등록</button>
</form>
<ul>
{comments.map((c) => (
<li className="border-b py-2" key={c.id}>{c.text}</li>
))}
</ul>
</div>
);
}
export default PostPage;
핵심1
const { posts, updatePost, deletePost } = useContext(PostContext);
-> deletePost 추가
핵심2
<button onClick={() => {deletePost(post.id); navigate('/');}}>삭제</button>
반응형
'프로그래밍 > React' 카테고리의 다른 글
| React로 블로그 만들기 - 사용자 인증 기능(로그인/로그아웃) (11) (0) | 2025.07.06 |
|---|---|
| React로 블로그 만들기 - 댓글 전역 상태 관리 (CommentContext) (10) (0) | 2025.07.06 |
| React로 블로그 만들기 - 간단한 UI 구성 및 레이아웃 구성하기 (8) (0) | 2025.07.06 |
| React로 블로그 만들기 - json-server 사용 (REST API mock) (7) (0) | 2025.07.06 |
| React로 블로그 만들기 - 데이터 저장 유지 – localStorage (6) (0) | 2025.07.06 |