Routing With app-route in NEXT 13(with Source Code and Live Demo)
The app-route
module is a built-in routing solution provided by NEXT.js. It simplifies the process of defining routes and handling navigation in your application
Setting Up a NEXT.js Project
npx create-next-app my-next-app
cd my-next-app
npm run dev
if you have selected src directory then the file structure would be:
open the local host mention in the terminal(in my case localhost:3000):
Creating Folder and files in src directiory:
make component folder in src directory and inside that folder make 2 new files Header.jsx & Footer.jsx
inside the file type the boilerplate command
rafce
(if it is not working download ES7 React from Extensions)import React from 'react' const Header = () => { return ( <div>Header</div> ) } export default Header
import React from 'react' const Footer = () => { return ( <div>Footer</div> ) } export default Footer
create some more pages under app directory and give them boilerplate code same as previous one
Example- About.jsx, Contact.jsx
clear everything inside return in page.js under app directory
export default function Home() { return ( <div> Home </div> ) }
Final file-structure:
Routing with app-route
Go to the layout.js and inside body tag add the the Header and Footer in a self-close tag and import the respective files
import Header from '@/components/Header' import './globals.css' import { Inter } from 'next/font/google' import Footer from '@/components/Footer' const inter = Inter({ subsets: ['latin'] }) export const metadata = { title: 'Create Next App', description: 'Generated by create next app', } export default function RootLayout({ children }) { return ( <html lang="en"> <body className={inter.className}> <Header /> {children} <Footer /> </body> </html> ) }
your output window should look like this:
-
As the Header and Footer tag wrapping the children props both header and footer will always be present no matter which page you are in.
Now Route the About and Contact page inside our Header.jsx
import Link from "next/link"; import React from "react"; const Header = () => { return ( <div> <Link href="/">Home</Link> <Link href="/about">About</Link> <Link href="/contact">Contact</Link> </div> ); }; export default Header;
Your Output should look like this:
Final Output:
Your app route is ready. Let's see the output
click on different routes and it will take you to the page
Source Code:
Subscribe to my newsletter
Read articles from ARITRA SARKAR directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by