Creating multiple layouts in Next.js based on your project's needs is a common practice. Let's explore

I have been working on the following starter project: https://github.com/vercel/nextjs-subscription-payments

The default content provided in the above link serves as the home page for my project.

Now, I am looking to create an admin and dashboard section with a different layout.

To achieve this, I have created the following routes:

app/dashboard/layout.tsx - Renamed as DashboardLayout
app/dashboard/page.tsx

For testing purposes, I copied the content from:

app/layout.tsx
app/page.tsx

The issue I am facing is that the header and footer are duplicated when accessing the dashboard page. It seems like the layout for the dashboard is still fetching content from the root app layout.tsx file.

If anyone has experience with this structure, I would appreciate some assistance.

Answer №1

It all comes down to what you require.

  1. If the layouts are similar, my recommendation is to tweak your existing navbar and footer for different pages. By doing this, you'll end up with less code overall.
  2. If the layouts are completely different, the best approach would be to add the navbar and footer to your child layout, while keeping the main layout without a header and footer.
  3. If, for some reason, your header and footer need to stay in the root layout, you can try hiding them on different pages. However, this might feel like a bit of a hacky solution and you may need to implement a page loader to prevent a double header/footer effect.
<html lang="en">
      <body className="bg-black loading">
        <SupabaseProvider>
          <main
            id="skip"
            className="min-h-[calc(100dvh-4rem)] md:min-h[calc(100dvh-5rem)]"
          >
            {children}
          </main>
        </SupabaseProvider>
      </body>
    </html>
const DashboardLayout = (children) => {
  return (
    <div>
     <DashboardNavbar/>
     {children}
     <DashboardFooter/>
    </div>
  )
}
export default DashboardLayout

Answer №2

If you're looking to keep the root layout separate from your dashboard page, I suggest utilizing the route group feature in Next.js.

Simply organize your pages and layouts into folders like this:

-- app
--- (layout1)
----- layout.tsx
----- dashboard.tsx
--- (layout2)
----- layout.tsx
----- page.tsx

This way, you can easily maintain distinct layouts for each page on the same level without interfering with the root layout structure.

Learn more about route groups in Next.js here.

Answer №3

Choosing the right approach depends on your specific requirements.

  1. If the layouts share similarities, it's recommended to customize your existing navbar and footer for various pages to reduce the overall amount of code.
  2. When dealing with completely different layouts, consider adding the navbar and footer to the child layout while excluding them from the main layout.
  3. In scenarios where the header and footer must remain in the root layout, one option is to hide them on certain pages. However, this workaround may be considered a temporary fix, possibly requiring the implementation of a page loader to prevent duplicate header and footer displays.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problems arising from the implementation of CSS modules in React applications

As a beginner in React, I recently started learning how to utilize CSS modules within my React projects. However, I encountered an error that read: Failed to compile. ./src/components/Header/Header.js Module not found: Can't resolve './Header.mo ...

Specifying data type in the fetch method

Screenshot depicting fetch function I'm currently working on a project using Next.js with Typescript and trying to retrieve data from a Notion database. I've encountered an error related to setting up the type for the database_id value. Can anyon ...

Encountering weathers.map is not a function error while using React.js with OpenWeatherMap integration

Struggling with React.js for a college project and need some help. The error message I keep encountering is: weathers.map not a function I know it's probably something simple, but for the life of me, I can't figure it out! My project structure f ...

Can React Router be integrated with Material UI tabs?

I have made some changes to the code of the Tabs component in material ui, <AppBar position="static"> <Tabs variant="fullWidth" value={value} onChange={handleChange} aria-label="nav tabs example" > < ...

Creating a task list without using JavaScript in the web browser and without relying on a database

Looking for some guidance on building a todo app for a job interview where JavaScript is disabled in the browser and no database can be used. Any JavaScript needs to be handled on the server side. I have some basic knowledge of node/express and serving H ...

Methods for invoking a function from a separate .js file within React Native Expo

I'm new to using React and I've come across a challenge: In my Main.js file, there is a button: import * as React from 'react'; import { StyleSheet, Text, View, SafeAreaView, Pressable, Alert } from 'react-native'; import { M ...

Error encountered while attempting to install react-router-dom using npm script

As I was in the middle of working on my React project, I decided to install react-router-dom. However, much to my surprise, it seems that this action caused all of my scripts and modules to disappear. Despite attempting various solutions such as cleaning w ...

The Sheet module of shadcn UI fails to close as expected

I am currently developing a basic navigation bar using Next.js along with the sheet component from shadcnui to manage the mobile version of the navigation. After clicking on a link in the mobile navbar, I get redirected correctly to the respective page. H ...

Troubleshooting the failure of implementing react hooks useState within a material-ui Tab container

Recently, I have been experimenting with implementing react-hooks useState in material-ui/tabs component. While I have been successful in using the handleChange function, I am eager to explore and master the use of hooks in this scenario. Interestingly, my ...

When using the DateTimePicker component in MUI with React, the displayed value may not always match the value that

When passing a value to the DateTimePicker component from '@mui/x-date-pickers/DateTimePicker, the displayed value sometimes shows a discrepancy of +2 hours or +1 hour. This issue may be related to timezones. For example: The value being passed: &apo ...

A guide on incorporating translated routes (by translating the route paths) within a NextJS application

I am currently working on a NextJS web application that will be deployed in multiple countries, with each deployment requiring changes only to the env.country variables. However, I am facing an issue with routes that have significant slugs needing translat ...

How come the array's length is not appearing on the browser screen?

Code: initialize: function() { this.todos = [ {id: 100, text: 'Rich'}, {id: 200, text: 'Dave'} ]; }, activeTodos: function() { this.todos = this.todos.length(function() { return this.todos; }); ...

Discussing the size of windows within React Material-UI's makeStyles framework

When I create a custom style for a specific component, my const declaration typically looks like this: const useStyles = makeStyles((theme: Theme) => createStyles({ screen: { margin: 0, padding: 0 }, surface: { backgroun ...

When toggling between different themes, the colors in Material-UI remain consistent and unchanged

Currently, I am adjusting the theme within my application by utilizing a state variable with the MuiThemeProvider. When I change to a new theme, all component colors update correctly. However, I have noticed that if I switch back to a previously used theme ...

I am struggling to display the data fetched by Next.js on the page

I am struggling to display the data from the first file in my tanstack table or as a string within the HTML, even though I can see it in a console.log when grabbed by axios. The tanstack table worked fine with hardcoded data. In the console image provided, ...

React Error boundary is failing to perform as anticipated

Having issues implementing an error boundary in React. Here is the code snippet: ErrorBoundary.js import React from 'react'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: fal ...

How does Stripe manage to bypass NextJS CORS restrictions?

I've got a Next.js 13 app with app routes that incorporate Stripe for processing payments. I have set up a route at app/api/webhook/route.ts to handle Stripe webhooks triggered after a client makes a purchase. Everything is working smoothly so far. Ho ...

What is the best way to invoke a function only once in typescript?

Struggling to implement TypeScript in React Native for fetching an API on screen load? I've been facing a tough time with it, especially when trying to call the function only once without using timeouts. Here's my current approach, but it's ...

The command 'push' fails to execute without displaying any error messages

My goal is to update the route when a user clicks a button. The code structure resembles the real-world example provided at real-world. Additionally, I have followed all the steps outlined in the documentation of react-router-redux. reducer/index.js: im ...

Do we still require the material-ui custom touch event? It seems to cause many issues

It has come to my attention that material-ui still relies on a package that appears to be incompatible with new React updates from Facebook. There seems to be some frustration over this issue, making it challenging to keep up with React advancements. Is th ...