Có cách nào khao báo Layout cho tất cả các trang không, không phải thủ công cho mỗi trang about.tsx

Có! ✅ Cách đúng và sạch nhất để dùng Layout cho tất cả các trang trong Next.js (kể cả khi bạn dùng next-i18next và cấu trúc [lang]) là đặt Layout vào _app.tsx.


✅ Cách dùng Layout toàn cục trong _app.tsx

1. Tạo component Layout nếu chưa có:

tsxCopyEdit// src/components/layout/Layout.tsx
import React from 'react';
import Navbar from './Navbar';
import Footer from './Footer';

type Props = {
  children: React.ReactNode;
};

export default function Layout({ children }: Props) {
  return (
    <div className="flex flex-col min-h-screen">
      <Navbar />
      <main className="flex-1">{children}</main>
      <Footer />
    </div>
  );
}

2. Sử dụng Layout trong _app.tsx

tsxCopyEdit// src/pages/_app.tsx
import { AppProps } from 'next/app';
import { appWithTranslation } from 'next-i18next';
import Layout from '@/components/layout/Layout';
import '@/styles/globals.css';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  );
}

export default appWithTranslation(MyApp);

Giờ toàn bộ các trang như /[lang]/about, /[lang]/contact... đều tự động có Layout mà không cần bạn phải import Layout thủ công trong từng file.


❗ Nếu bạn muốn một số trang dùng Layout khác, bạn có thể:

Cách nâng cao: Cho phép override layout theo trang

tsxCopyEdit// src/pages/_app.tsx
import type { AppProps } from 'next/app';
import type { NextPage } from 'next';
import { appWithTranslation } from 'next-i18next';
import Layout from '@/components/layout/Layout';
import '@/styles/globals.css';

type NextPageWithLayout = NextPage & {
  getLayout?: (page: React.ReactNode) => React.ReactNode;
};

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout;
};

function MyApp({ Component, pageProps }: AppPropsWithLayout) {
  const getLayout = Component.getLayout ?? ((page) => <Layout>{page}</Layout>);
  return getLayout(<Component {...pageProps} />);
}

export default appWithTranslation(MyApp);

✅ Và giờ bạn có thể làm:

tsxCopyEdit// src/pages/[lang]/no-layout-page.tsx
function NoLayoutPage() {
  return <div>This page has no layout</div>;
}

NoLayoutPage.getLayout = (page: React.ReactNode) => page;

export default NoLayoutPage;

Bạn muốn mình cập nhật lại _app.tsxLayout.tsx từ project bạn đã gửi để bạn copy/paste lại không?

Last updated

Was this helpful?