[Docs] Post / Index 페이지 다듬기
Post 페이지 - Headtitle 추가하기
pages/posts/[id].js 파일 상단에 임포트를 추가하고 <title> 태그를 추가한다.
// Add this import
import Head from 'next/head';
export default function Post({ postData }) {
return (
<Layout>
{/* Add this <Head> tag */}
<Head>
<title>{postData.title}</title>
</Head>
{/* Keep the existing code here */}
</Layout>
);
}
날짜 형식 지정하기
date-fns 라이브러리를 사용해 보려고 한다.
npm install date-fns 하여 설치 후 components/date.js 파일을 생성하고 Date 컴포넌트를 추가한다.
date-fns 웹사이트에서 다양한 format() 문자열 옵션을 확인할 수 있는데 이번엔 'January 1, 2020'과 같이 표시한다.
import { parseISO, format } from 'date-fns';
export default function Date({ dateString }) {
const date = parseISO(dateString);
return <time dateTime={dateString}>{format(date, 'LLLL d, yyyy')}</time>;
}
pages/posts/[id].js 파일 상단에 임포트를 추가하고 내용도 업데이트한다.
// Add this import
import Date from '../../components/date';
export default function Post({ postData }) {
return (
<Layout>
{/* Keep the existing code here */}
{/* Replace {postData.date} with this */}
<Date dateString={postData.date} />
{/* Keep the existing code here */}
</Layout>
);
}
CSS 추가하기
앞서 생성했던 styles/utils.module.css 파일을 사용해 CSS를 업데이트한다.
pages/posts/[id].js를 열고 CSS 파일에 대한 임포트를 한 다음 Post 컴포넌트를 다음 코드로 바꾼다.
// Add this import at the top of the file
import utilStyles from '../../styles/utils.module.css';
export default function Post({ postData }) {
return (
<Layout>
<Head>
<title>{postData.title}</title>
</Head>
<article>
<h1 className={utilStyles.headingXl}>{postData.title}</h1>
<div className={utilStyles.lightText}>
<Date dateString={postData.date} />
</div>
<div dangerouslySetInnerHTML={{ __html: postData.contentHtml }} />
</article>
</Layout>
);
}
이제 http://localhost:3000/posts/pre-rendering 에 접속하면 이제 페이지가 조금 더 보기 좋게 표시된다.
Index 페이지
이제 인덱스 페이지(pages/index.js)를 업데이트해보자.
Link 컴포넌트를 사용해서 각 글 페이지에 링크를 추가할 필요가 있다.
pages/index.js를 열고 파일 상단에 Link 및 Date에 대해 아래 임포트를 추가한다
import Link from 'next/link';
import Date from '../components/date';
그리고 Home 컴포넌트 li 태그를 다음과 같이 바꿔준다.
<li className={utilStyles.listItem} key={id}>
<Link href={`/posts/${id}`}>{title}</Link>
<br />
<small className={utilStyles.lightText}>
<Date dateString={date} />
</small>
</li>
http://localhost:3000을 확인해 보면 각 포스트로 연결되는 링크가 표시된다.