Containers shared among Next.js pages within a folder

Is it possible to have a shared container for all pages within a specific folder in NextJS?

One potential solution could involve the following code:

// pages/folder/index.js
export default function Container({ children }) {
    return <Container>{children}</Container>
}

// pages/folder/child.js
export default function Child() {
    return <Child />
}

Answer №1

For the solution you seek, consider exploring Layouts.

// components/layout.js

import Navbar from './navbar'
import Footer from './footer'

export default function Layout({ children }) {
  return (
    <>
      <Navbar />
      <main>{children}</main>
      <Footer />
    </>
  )
}

Creating a Single Shared Layout with Custom App

// pages/_app.js

import Layout from '../components/layout'

export default function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  )
}

Different Layouts for Each Page

// pages/index.js

import Layout from '../components/layout'
import NestedLayout from '../components/nested-layout'

export default function Page() {
  return (
    /** Your content */
  )
}

Page.getLayout = function getLayout(page) {
  return (
    <Layout>
      <NestedLayout>{page}</NestedLayout>
    </Layout>
  )
}
// pages/_app.js

export default function MyApp({ Component, pageProps }) {
  // Use the layout defined at the page level, if available
  const getLayout = Component.getLayout || ((page) => page)

  return getLayout(<Component {...pageProps} />)
}

Answer №2

One challenge with NextJS is the lack of consensus within the community regarding shared state and layout management.

To overcome this issue, my team at work found a solution by utilizing a custom app component. Another option, as mentioned by @rantao, is to implement a layout.

/* _app.js */
export default function _App({ Component, pageProps }){
    const navigationEnabled = Component?.navigation ?? true;
    const footerEnabled = Component?.footer ?? true;

    // This is just an example. Feel free to customize your own components and layout.
    return <>
        { navigationEnabled === true && <Navigation />}
        <Component {...pageProps />
        { footerEnabled === true && <Footer />}
    </>;
}

/* page.js */
export default function Page(){}
// Don't display the navigation on this page. 
Page.navigation = false; 

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

Struggling to pass Chai tests with Node and Express.js when trying to handle POST requests

Working through a Chai testing exercise and struggling to pass the POST route tests. Encountering two specific errors: 1) Todo API: POST /v1/todos Issue with creating and returning new todo using valid data: Header 'location' should ...

"Enhance your website with dynamic uploader forms and AJAX scripts - Railscast #383 shows you

I've successfully implemented the uploader functionality from Railscast #383, but I'm wondering if it's possible to dynamically add and remove the uploader link using ajax? Additionally, I'd need to include the "service" instance id wh ...

The printing function for the window system can cause disruptions to the layout of the table

After creating a page with a simple table that can be filled in and printed, I noticed some issues with the table formatting after printing. The intended table design was supposed to look like this: https://i.stack.imgur.com/aAk89.png However, upon print ...

Display or conceal various objects using a single button in HTML

I've been working on creating a chatbot widget for my website, but I've run into an issue. The "Chat with us" button only shows the bot and not the close button as well. Here's what I've attempted: <input id="chat" type="button" on ...

The content at “http://localhost:3000/script.js” could not be accessed because of a MIME type mismatch with the X-Content-Type-Options set to nosniff

I encountered an issue while attempting to transfer all the JavaScript to a separate js file and then adding that js file to the html per usual. The console displayed the following error message: The resource from “http://localhost:3000/public/main.js” ...

I am having trouble with my Vue nested For loop as it is only returning the first value of the second array. What could be

I am currently utilizing a nested For loop to retrieve data from JSON and then returning a variable for Vue frontend access. Oddly enough, I am only able to retrieve values from the initial element of the nested array. Can anyone assist with this issue? It ...

Adjusting webpage zoom based on different screen sizes

Hey there, I ran into an issue with my web page design. It looks great on my desktop monitors, but when I checked it on my laptop, things went haywire. Strangely, adjusting the zoom to 67% seemed to fix the problem. Both screens have a resolution of 1920 ...

How to Retrieve the Access Token from Instagram using Angular 2/4/5 API

I have integrated Instagram authentication into my Angular 2 project using the following steps: Begin by registering an Instagram Client and adding a sandbox user (as a prerequisite) Within signup.html, include the following code snippet: <button t ...

Incorporating a setup file into my JavaScript project

In my JavaScript project, I have both frontend and backend codes (NodeJS). Here is the folder structure for my production environment: /prod /server sourceCode1.js sourceCode2.js ... sourceCodeN.js index.js ...

Access a JSON value in the Google Sheets script editor and retrieve the data

I'm trying to retrieve a value from a JSON object by making an API call in a Google Sheet. Below is the script I am using: function getBitcoinPrice() { var url = "https://acx.io//api/v2/tickers/btcaud.json"; var response = UrlFetchApp.fetc ...

Switching between light and dark mode in Chakra UI Next Js takes an extra tap on Mobile devices to update the Background Color

I encountered an unusual issue while trying to set up a ColorMode Toggle on a NextJs project using Chakra UI for light and dark modes. After following the documentation and implementing it accordingly, I noticed that everything works as expected on deskto ...

Having issues with Next.js server-side rendering when integrating API functionality

"Not building properly" means that the project is not fully completing the build process. I've developed a simple blog project with dynamic SSR that pulls data from the Notion-API to generate static blog pages. Everything functions correctly ...

The validity of the return statement in the ajax code is malfunctioning

Currently, I am in the process of validating duplicate email addresses from a database. Initially, I validate the email format, then check the email length and finally verify the email with the database using ajax. However, the return true or return false ...

How to toggle between two background colors in a webpage with the click of a button using JavaScript

I need help with a unique website feature. I want to implement a button that cycles between two different background colors (white and black) as well as changes the font color from black to white, and vice versa. My goal is to create a negative version of ...

In JavaScript, constructors do not have access to variables

Currently, I am attempting to implement Twilio Access Token on Firebase Functions using TypeScript. export const generateTwilioToken = functions.https.onRequest((req, res) => { const twilioAccessToken = twilio.jwt.AccessToken; const envConfig = fun ...

Vue: Displayed list displaying checked checkboxes

My attempt at displaying the selected checkboxes is as follows: <pre>{{ JSON.stringify(selectedAttributes, null, 2) }}</pre> <ul class="list-unstyled" v-for="category in categories" ...

Insert DOM elements at the start of the parent element

I'm currently using the following JavaScript code to insert AJAX responses into a div with an ID of results: document.getElementById("results").innerHTML=xmlhttp.responseText; The issue I am encountering is that this code adds all new elements after ...

Integrating a search box with radio buttons in an HTML table

I am currently working on a project that involves jQuery and a table with radio buttons. Each button has different functionalities: console.clear(); function inputSelected(val) { $("#result").html(function() { var str = ''; ...

Refreshing the Angular resource under observation

My brain feels a bit fried today, so pardon what might seem like an obvious question. I have a useful resource at my disposal: Book = $resource("/books/:id", {id: "@id"}); book = Book.get(1); When I want to refresh the object to receive any updates from ...

When attempting to submit data, the Magnific Popup page is restored to its default format

I am facing an issue with my Magnific Popup page: function dataLink(){ $.magnificPopup.open({ items: { src: 'datapage.html', type: 'ajax' }, closeOnContentClick : false, clos ...