반응형
이제 블로그 페이지에 서버에 저장되어 있는 댓글(comment)을 불러오는 작업을 하겠습니다.
그렇게 하기 위해 우선은 components폴더 안에 댓글의 리스트를 보여줄 CommentsList.js파일을 생성해주고 코드는 다음과 같이 작성합니다.
CommentsList.js
const CommentsList = ({ comments }) => (
<>
<h3>Comments:</h3>
{comments.map(comment => (
<div className="comment" key={comment.postedBy + ': ' + comment.text}>
<h4>{comment.postedBy}</h4>
<p>{comment.text}</p>
</div>
))}
</>
);
export default CommentsList;
ArticlePage.js
import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import axios from 'axios';
import NotFoundPage from './NotFoundPage';
import CommentsList from '../components/CommentsList';
import articles from './article-content';
const ArticlePage = () => {
const [articleInfo, setArticleInfo] = useState({ upvotes: 0, comments: [] });
const { articleId } = useParams();
useEffect(() => {
const loadArticleInfo = async () => {
const response = await axios.get(`/api/articles/${articleId}`);
const newArticleInfo = response.data;
setArticleInfo(newArticleInfo);
}
loadArticleInfo();
}, []);
const article = articles.find(article => article.name === articleId);
if (!article) {
return <NotFoundPage />
}
return (
<>
<h1>{article.title}</h1>
<p>This article has {articleInfo.upvotes} upvote(s)</p>
{article.content.map((paragraph, i) => (
<p key={i}>{paragraph}</p>
))}
<CommentsList comments={articleInfo.comments} />
</>
);
}
export default ArticlePage;
결과 화면은 다음과 같습니다.
반응형
'PROGRAMING > FULL STACK' 카테고리의 다른 글
[Front End - Back End] Creating an add comment form (0) | 2024.03.21 |
---|---|
[Front End - Back End] Creating an upvote button (0) | 2024.03.21 |
[Front End - Back End] Adding data loading to page components (0) | 2024.03.21 |
[Front End - Back End] Adding React hooks (0) | 2024.03.21 |
[Front End - Back End] The Axios library (0) | 2024.03.21 |