I have a Next JS app, the version is 13.5.4, its structured like this:
- pages
-- about.tsx
- src
-- app
--- layout.tsx
--- page.tsx
In order to not repeat code, I changed the default layout.tsx to this:
import './globals.scss'
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import {Navbar} from "@/app/components/Navbar/navbar";
import {Footer} from "@/app/components/Footer/footer";
const inter = Inter({ subsets: ['latin'] })
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className={inter.className}>
<Navbar /> // ---- added this
{children}
<Footer /> // ---- added this
</body>
</html>
)
}
My goal is to have Navbar and Footer on every page by default. Now the problem is, they are on homepage, i.e. applied to page.tsx. But they are not on /about. Any idea why?
Here is the navbar.tsx which routes to the /about.
import Link from "next/link";
export const Navbar = () => {
return (
<nav>
<div>
<ul>
<li>
<Link href="/#">Home</Link>
</li>
<li>
<Link href="/about">About</Link>
</li>
</ul>
</div>
</nav>
)
}
2
Answers
Thanks to @evolutionxbox, I found the answer on official doc: https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration#migrating-from-pages-to-app here The solution is:
/pages/_document.tsx
as follows:/pages/_app.tsx
as follows:Then there should be no need to add
import
in the/src/app/page.tsx
or/pages/about.tsx
, they should simply be like:Since there’s going to be only the Navbar exported, Instead of exporting the NavBar using an arrow function can you declare
Navbar
as a function and then export it as default?Like
and then import it using,