본문 바로가기
STUDY/Project

마무리 작업 - HomePage, 이동버튼 추가

by Y.Choi 2025. 5. 8.
728x90
반응형

 

끝이라서 마무리 작업이아니라 시작을 위한 마무리라고 볼 수 있겠다.

아직 css나 레이아웃을 적용하지 않아서 이쁘진 않지만 기능은 어느정도 기본을 갖춘 홈페이지가 되었다. 

좀 더 자연스런 흐름을 갖도록 몇가지를 추가한다. 

그러나, 이번 작업은 임시적인 것이다. 

 

 

| 메인 페이지 작성

 

프로젝트를 npm run dev로 실행하게 되면 http://localhost:3000 페이지가 열리는데 아직 루트 페이지를 지정하지 않아서 빈화면이 뜰 것이다. 메인 페이지를 만들어 루트로 지정하고 게시글 목록과 로그인 버튼이 보이게 해본다.

 

frontend/src/pages/HomePage.js

import React, { useEffect, useState, useContext } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { AuthContext } from '../context/AuthContext';

const HomePage = () => {
  const [posts, setPosts] = useState([]);
  const { user, logout } = useContext(AuthContext);

  useEffect(() => {
    const fetchPosts = async () => {
      try {
        const res = await axios.get('http://localhost:5000/api/posts');
        setPosts(res.data);
      } catch (err) {
        console.error(err);
      }
    };
    fetchPosts();
  }, []);

  return (
    <div>
      <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h1>📋 게시판</h1>
        <div>
          {user ? (
            <>
              <span>{user.username}님</span>
              <button onClick={logout} style={{ marginLeft: '10px' }}>로그아웃</button>
            </>
          ) : (
            <Link to="/login"><button>로그인</button></Link>
          )}
        </div>
      </header>

      <ul>
        {posts.map(post => (
          <li key={post._id}>
            <Link to={`/posts/${post._id}`}>{post.title}</Link> — {post.author.username}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default HomePage;

 

 

| 라우터 추가

 

frontend/src/routes/authRoutes.js

<Route path="/" element={<HomePage />} />

 

 

 

로그인시에는 사용자 이름과 로그아웃 버튼이 보인다. 

 

 

 

| 대시보드에 게시판 버튼 추가

 

로그인 후 대시보드로 이동하는데 아직 메뉴와 같은 기능을 만들지 않아서 게시판으로 이동이 불편할 것이다. 게시판 버튼을 만들고 버튼을 클릭하면 게시판 목록으로 이동한다.

 

frontend/src/pages/DashboardPage.js

import React, { useContext } from 'react';
import { AuthContext } from '../context/AuthContext';
import { useNavigate, Link } from 'react-router-dom';

const DashboardPage = () => {
  const { user, logout } = useContext(AuthContext);
  const navigate = useNavigate();

  if (!user) {
    return <p>로그인이 필요한 페이지입니다. 🔒</p>;
  }

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  return (
    <div>
      <h2>대시보드 🧭</h2>
      <p>환영합니다, {user.username}님!</p>
      <button onClick={handleLogout}>로그아웃</button>

      <div style={{ marginTop: '1rem' }}>
        <Link to="/posts">
          <button>📄 게시판 </button>
        </Link>
      </div>
    </div>
  );
};

export default DashboardPage;

 

 

 

 

 

| 게시판 목록에 글쓰기 버튼 추가

 

로그인한 사용자만 글쓰기가 가능하기 때문에 AuthContext를 사용해 로그인시에만 볼 수 있는 글쓰기 버튼을 추가한다. 

 

frontend/src/pages/PostListPage.js

import React, { useEffect, useState, useContext } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import { AuthContext } from '../context/AuthContext';

const PostListPage = () => {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const { user } = useContext(AuthContext);

  useEffect(() => {
    const fetchPosts = async () => {
      try {
        const res = await axios.get('http://localhost:5000/api/posts');
        setPosts(res.data);
      } catch (err) {
        console.error('게시글 목록 로드 실패:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchPosts();
  }, []);

  if (loading) return <p>로딩 중...</p>;

  return (
    <div>
      <h2>📚 게시판</h2>
      {user && (
        <Link to="/posts/create">
          <button>✍ 글쓰기</button>
        </Link>
      )}

      {posts.length === 0 ? (
        <p>게시글이 없습니다.</p>
      ) : (
        <ul>
          {posts.map((post) => (
            <li key={post._id}>
              <Link to={`/posts/${post._id}`}>
                <strong>{post.title}</strong>
              </Link>{' '}
              <span>- {post.author.username}</span>{' '}
              <span>({new Date(post.createdAt).toLocaleDateString()})</span>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default PostListPage;

 

 

 

 

 

이렇게 1차적으로 프로젝트가 끝났다.

UI적인 부분이 형편없어서 마무리로 끝내기엔 마음에 들진 않는데 그렇기 때문에 계속 발전해 나갈 수 있다.

 

두 번째로는 ...

아무래도 UI 부터 어떻게 해봐야겠다. 😁

728x90
반응형