다뤄야 할 내용
글 작성과 수정에서 공통으로 사용하는 폼 컴포넌트를 분리하여 재사용성 향상
폼 컴포넌트 분리
src/
└── components/
└── PostForm.jsx
PostForm.jsx
// src/components/PostForm.jsx
import { useState } from 'react';
function PostForm({ initialTitle = '', initialContent = '', onSubmit, submitLabel = "등록" }) {
const [title, setTitle] = useState(initialTitle);
const [content, setContent] = useState(initialContent);
const handleSubmit = e => {
e.preventDefault();
if (!title.trim() || !content.trim()) {
alert("제목과 내용을 모두 입력하세요.");
return;
}
onSubmit(title, content);
};
return (
<form onSubmit={handleSubmit}>
<input
placeholder="제목"
value={title}
onChange={e => setTitle(e.target.value)}
/>
<br />
<textarea
placeholder="내용"
value={content}
onChange={e => setContent(e.target.value)}
/>
<br />
<button type="submit">{submitLabel}</button>
</form>
);
}
export default PostForm;
컴포넌트 PostForm.jsx 적용시키기
WritePage.jsx 수정 (폼 사용)
import { useContext } from 'react';
import { PostContext } from '../context/PostContext';
import { useNavigate } from 'react-router-dom';
import PostForm from '../components/PostForm';
function WritePage() {
const { addPost } = useContext(PostContext);
const navigate = useNavigate();
const handleAdd = (title, content) => {
addPost(title, content);
navigate('/');
};
return (
<div>
<h2>글 작성</h2>
<PostForm onSubmit={handleAdd} submitLabel="등록" />
</div>
);
}
export default WritePage;
PostPage.jsx에서 수정 시 PostForm 재사용
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 } = 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>{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로 블로그 만들기 - json-server 사용 (REST API mock) (7) (0) | 2025.07.06 |
|---|---|
| React로 블로그 만들기 - 데이터 저장 유지 – localStorage (6) (0) | 2025.07.06 |
| React로 블로그 만들기 - 글 상세 보기 + 수정 기능 + 댓글 기능 구현 (4) (0) | 2025.07.06 |
| React로 블로그 만들기 - 글 데이터 상태 관리 (useState + Context) (3) (0) | 2025.07.06 |
| React로 블로그 만들기 - 라우팅 구성하기(2) (0) | 2025.07.06 |