Simplifying Next.Js App-Directory

ยท

3 min read

Simplifying Next.Js App-Directory

If you were working on the previous versions of Next.js then you might be very much familiar with the page directory, where the developer can create a file inside the page directory and it will be acting as a route.

For example: Creating a file like -> pages/about.tsx will be resulting in creating a route as "test.com/route".

While working with the app directory which is one of the latest features the next js makes file structure much easier to organize for the developers. The route is controlled by the folder name inside the app directory.

For example: Creating a file like -> app/about/page.tsx will be resulting in creating a route as "test.com/route".

What if there is a situation where we will be needing routes like "test.com/projects/frontent"? ๐Ÿค”

To handle this kind of situation we need to structure the folder like -> app/projects/frontend/page.tsx.

So what's next? Are you thinking the same as what I'm thinking?

How can we use params in routing?

To handle this we need to structure the folder like -> app/profile/[id]/page.tsx.

This will lead to a route like "test.com/profile/2".

Along with this app directory also brought us different things like loading, layout, and error components.

Layout :

Consider where a situation you need a common layout shared across various pages, that's where layout.ts comes into action. To create a layout file simply create react component with the contents you need and it should accept the {children} prop inside.

export default function DummyLayout({children}: {children: React.ReactNode}) {
  return (
    <div>
      {/* Include your shared component here*/}
      {children}
    </div>
  )
}

On navigating inside the layout, it will preserve the state and won't be re-rendering.

Loading Component:

A specific file named loading.tsx is solely available for handling the loading state in your website. This file will help you create a proper loading UI for your website.

A loading file's content will be looking like this,

export const Loading = () => {
return (
{your custom loader}
)
}

The loading file should be added inside the layout and it should be wrapped with <Suspense> around your main content.

export default function Dummy() {
  return (
    <div>
      <Suspense fallback={<Loading/>}>
        <Content />
      </Suspense>
    </div>
  )
}

Error Component :

We can handle the error by adding an error ui by creating a file as error.ts. Whenever the runtime error appears we can handle it safely with our error ui.

An error ui component can be created something like :

export default function Error({error,reset}: {
  error: Error
  reset: () => void
}) {
  return (
    <div>
      <h2>Oh no Error!</h2>
      <button onClick={() => reset()}>
        Reload
      </button>
    </div>
  )
}

And we can to the end of the blog, hope you like the content, and feel free to add your thoughts in the comments.

ย