NEXT JS: Project Structure

NEXT JS: Project Structure

PART II

ยท

2 min read

Routing Files Convention

Layout.tsx File

is the main entry point of our application and all of the components are wrapped within it as its children

  • Enables you to personalize the behavior of your application by providing a common layout or template for all of the pages any components you include in this file will be shared throughout your entire application

    • As a result any code you write within this file such as a P tag hello world will be displayed on every route page
  • also allows you to customize the appearance of your HTML document so you can set things like language, modify the metadata for all the pages, add script tags, redux provider, links or even fonts

import { Inter } from 'next/font/google'
import './globals.css'

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}>{children}</body>
    </html>
  )
}

Page.tsx File

A page is UI that is unique to a route.

export default function Page({
  params,
  searchParams,
}: {
  params: { slug: string }
  searchParams: { [key: string]: string | string[] | undefined }
}) {
  return <h1>My Page</h1>
}

Loading.tsx

A loading file can create instant loading states built on Suspense.

export default function Loading() {
  // Or a custom loading skeleton component
  return <p>Loading...</p>
}

Error.tsx

Error components must be Client Components

An error file defines an error UI boundary for a route segment.

It is useful for catching unexpected errors that occur in Server Components and Client Components and displaying a fallback UI.

'use client' // Error components must be Client Components

import { useEffect } from 'react'

export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string }
  reset: () => void
}) {
  useEffect(() => {
    // Log the error to an error reporting service
    console.error(error)
  }, [error])

  return (
    <div>
      <h2>Something went wrong!</h2>
      <button
        onClick={
          // Attempt to recover by trying to re-render the segment
          () => reset()
        }
      >
        Try again
      </button>
    </div>
  )
}

REFERENCE

ย