not-found.tsx 데모
not-found.tsx는 notFound() 함수가 호출되었을 때 표시되는 커스텀 404 UI를 정의합니다. 아래 버튼을 클릭하여 직접 확인하세요.
routing-files/not-found-demo/
├── not-found.tsx ← 커스텀 404 UI
└── page.tsx ← 현재 페이지핵심 코드
// not-found.tsx
const NotFound = () => {
return (
<div>
<h2>페이지를 찾을 수 없습니다</h2>
<p>요청한 리소스가 존재하지 않습니다.</p>
</div>
);
};
export default NotFound;
// page.tsx 또는 서버 컴포넌트에서
import { notFound } from 'next/navigation';
const Page = async (props) => {
const data = await fetchData(props.id);
if (!data) notFound(); // → not-found.tsx 렌더링
return <div>{data.title}</div>;
};설명
notFound()함수는next/navigation에서 import합니다.- 가장 가까운 상위의 not-found.tsx가 렌더링됩니다.
- 데이터 페칭 후 리소스가 없을 때 사용하는 것이 일반적입니다.
- app/not-found.tsx는 전체 앱의 기본 404 페이지가 됩니다.