글 상세 보기 (PostPage)
import { useContext, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { PostContext } from '../context/PostContext';
function PostPage() {
const { posts, updatePost } = useContext(PostContext);
const { id } = useParams();
const post = posts.find(p => p.id === Number(id));
const navigate = useNavigate();
const [editing, setEditing] = useState(false);
const [editTitle, setEditTitle] = useState(post?.title || '');
const [editContent, setEditContent] = useState(post?.content || '');
// 댓글 관련
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('');
};
const handleUpdate = () => {
updatePost(post.id, editTitle, editContent);
setEditing(false);
};
if (!post) return <p>글을 찾을 수 없습니다.</p>;
return (
<div>
{editing ? (
<>
<input
value={editTitle}
onChange={e => setEditTitle(e.target.value)}
/>
<textarea
value={editContent}
onChange={e => setEditContent(e.target.value)}
/>
<button onClick={handleUpdate}>저장</button>
<button onClick={() => setEditing(false)}>취소</button>
</>
) : (
<>
<h2>{post.title}</h2>
<p>{post.content}</p>
<button onClick={() => setEditing(true)}>수정하기</button>
<button onClick={() => navigate(-1)}>뒤로가기</button>
</>
)}
<hr />
<h3>댓글</h3>
<form onSubmit={handleCommentSubmit}>
<input
type="text"
placeholder="댓글을 입력하세요"
value={commentText}
onChange={e => setCommentText(e.target.value)}
/>
<button type="submit">등록</button>
</form>
<ul>
{comments.map(c => (
<li key={c.id}>{c.text}</li>
))}
</ul>
</div>
);
}
export default PostPage;
실행하기
npm run dev반응형
'프로그래밍 > React' 카테고리의 다른 글
| React로 블로그 만들기 - 데이터 저장 유지 – localStorage (6) (0) | 2025.07.06 |
|---|---|
| React로 블로그 만들기 - 폼 컴포넌트 분리 및 재사용 (5) (0) | 2025.07.06 |
| React로 블로그 만들기 - 글 데이터 상태 관리 (useState + Context) (3) (0) | 2025.07.06 |
| React로 블로그 만들기 - 라우팅 구성하기(2) (0) | 2025.07.06 |
| React로 블로그 만들기 - 프로젝트 생성하기(1) (0) | 2025.07.06 |