The layout in Nextjs _app does not stay constant; it refreshes with each page change

After creating a _app.js file:

const MyApp = ({Component, pageProps})  => {

    const getLayout = Component.getLayout || ((page) => <Layout>{page}</Layout>)
    
    return getLayout(<Component {...pageProps} />)

}
export default MyApp

I also have two pages, about.js and works.js, which simply return an empty div:

export default function Works(){
    return(
        <div></div>
    )
}

The default layout is defined as follows:

const Layout = ({children}) => {
    return (
        <div>
            <Navbar/>
            <main>{children}</main>
        </div>
    );
};
export default Layout;

However, when navigating from /works to /about using the navbar link:


...
<div className={styles.item}><a href={'/about'}>about</a></div>
...

It still loads the Navbar for some reason. I am using Next.js 13.2.3 and I can't seem to figure out why this isn't working as expected.

I've already attempted removing per-page layouts and opting for a shared layout for all pages, but it resulted in the same issue. So, I reverted back to per-page layouts, as I specifically need the default page without the Navbar, while other pages should include it.

Despite searching for solutions on StackOverflow, nothing has resolved my problem. I am now trying to identify what's causing this unexpected behavior in my code.

Answer №1

After some digging, I finally figured out the answer to my problem. Instead of using <a> Components for page transitions, I should be using <Link> from next/link :D

<div className={styles.item}><Link href={'/about'}>about</Link></div>

Answer №2

Insert the following code snippet into your _app.js file

import "@/styles/globals.css";
import MyLayout from "@/components/layouts/layout";
import Navbar from "@/components/Navbar/Navbar";
import Layout from "@/components/layouts/layout";


const MyApp = (props)  => {  
  const { Component, pageProps } = props;
  
    return (
      <Layout>
       <Component {...pageProps} />
      </Layout>
    );

}
export default MyApp

Paste the code below into your layout.js file

import React from "react";
import Navbar from "../Navbar/Navbar";
import Head from "next/head";
import  {useRouter} from 'next/router'

const Layout = ({children}) => {
    const router = useRouter();

    return (
        <div>
            {router.asPath === '/' ? null : <Navbar/>}
            <main>{children}</main>
        </div>
    );
};

export default Layout;

This layout will be displayed on all pages except for the /about page

PS: I had to separately run

❯ npm i <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7a5b2b6b4a3fabab8bab2b9a397e6f9e6f9e4">[email protected]</a>  
in order to execute your project

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

Exploring the possibilities of using React for looping?

I have integrated Dexie.js with React for this specific example. However, the implementation details are not of great importance to me. My main focus is on finding out how to iterate through all objects in my IndexDB database using React. In the code snip ...

The challenge of PHP's HTTP_REFERER

I am experiencing an issue with http_referer. In my setup, I have two files: index.php and index.html. The index.php file contains a form that, upon submission, includes information like the http_referer. On the other hand, the index.html file runs an aja ...

Tips for incorporating line breaks into a contenteditable div using the key combination of ctrl + enter

$("#contenteditable").keydown(function(e) { var last = false; if (e.keyCode == 13) { if (e.ctrlKey) { let brNode = document.createElement('br'); let range = window.getSelection().getRangeAt(0); ...

obtain the content of a TextField element

In my React component that utilizes MaterialUI, I have created a simple form with a text field and a button: export default function AddToDo() { const classes = useStyles(); return ( <div style={{ display: "flex" }} ...

How to run 'npm' scripts externally in package.json on Windows?

In the world of development, running arbitrary commands using npm run is a common practice. This involves adding a scripts hash to your package.json: "scripts": { "build-js": "browserify browser/main.js | uglifyjs -mc > static/bundle.js" } To exec ...

Using the Jquery validation plugin for Internet Explorer 9 when the website first loads

Our website is currently using Jquery v1.9.0 and jquery validation plugin v1.10.0. The form on our site consists of two text boxes and a submit button. When the submit button is clicked, the input elements are validated and a JavaScript function is trigger ...

Utilizing AngularJS and Node.js to update MongoDB

Looking for a solution to update my MongoDB using Node.js and AngularJS within the front-end of my application. The code I currently have is causing an error stating `TypeError: Cannot read property 'put' of undefined. Here is my AngularJS contr ...

Angular JS: Automatically toggle the visibility of a div on a panel click event

There is a row, panel, and a closed div on load. Clicking on the panel should make the div appear while making the row and panel disappear. Clicking on X should make the panel and row appear again. <script src="https://ajax.googleapis.com/ajax/libs/ ...

Perform an Ajax POST request to a specific URL and then automatically redirect to that same

I am currently in the process of developing a web application that allows users to create markers on a Leaflet map. The marker details are then saved in a Django backend system. My objective is to direct the user to a detailed page where they can input mar ...

Modify the value of a CSS property through JavaScript

Hey there, I'm wondering how to change a CSS value of the document itself, rather than targeting a specific element. I've already looked into solutions like Change :hover CSS properties with JavaScript, but they all involve adding CSS rules. I a ...

Utilizing PHP variables to dynamically assign names to radio input tags, and then extracting their values using jQuery or JavaScript

I am facing an issue with my PHP file that generates radio buttons based on unique pets ids. The variable $idperro is constantly changing to distinguish the set of radio buttons. My goal is to insert the value inside the p tag. Here's the PHP code sn ...

The function estimatedDocumentCount() actually returns an object rather than a numerical value

I am currently working on a feature in my web application where I want to display the number of documents stored in my MongoDB database whenever a user visits the homepage. To achieve this, I have outlined the implementation process in the following diagra ...

Experiencing difficulties when trying to pan and zoom the data obtained from d3.json within a line chart

I am currently working on developing a trend component that can zoom and pan into data fetched using d3.json. Here is the code I have written so far: <script> var margin = { top: 20, right: 80, bottom: 20, left: 50 }, width = $("#trendc ...

Attempting to update information in JSON using AJAX and PHP

I am attempting to update key values in a JSON object using PHP, AJAX, and JavaScript to display the new values. Here is an example of my JSON database that needs to be modified: "answer01count": "1", "answer02count": "2", "answer03count": " ...

Add up the duplicate elements in two arrays

I have dynamically created two arrays with the same number of cells (where array.length is the same, representing a key and value association). Below are the arrays: barData.labels["Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "F ...

How can AngularJS ng-repeat be used to extract HTML elements?

I need help parsing HTML that is received from the server as a string. Here is an example of what I receive: <img src="http://gravatar.com/avatar/9a52267d32ad2aaa4a8c2c45b83396e5?d=mm&amp;s=&amp;r=G" class=" user-1-avatar avatar- photo" width=" ...

Incorporating live text into a tag while arranging items by price in both ascending and descending order

I recently added a button to my online shop that allows users to sort products by price, even though I don't fully understand the underlying JavaScript code. I want to enhance this button by updating the text to indicate whether the sorting order is ...

Utilizing Next.js in React.js, one can easily import JPG images into their project. When importing multiple images

I have a React app where I import images in various scales and display them. Some images are imported correctly, but some end up with long and "strange" string names instead of their regular file names. For example: import generator from '../images/ ...

Creating accurate endpoints in an isolated Docker network using NextJS and Nginx: Best practices

I am facing an issue with my Docker network configuration. I have set up an isolated network and a reverse proxy to serve the NextJS app on localhost. However, whenever I try to fetch data from the backend through the browser, it fails. Strangely, when I u ...

Tips for interpreting information from a JSON array that has been stringified, looping through the data, and utilizing it effectively

I'm currently exploring Node JS packages and I need some guidance. Here is an example of the JSON data that I have: [{ "name":"SpiderMan", "description":"Superhero", "head_id":"29", "domain_name":"spiderman.com" }] I am trying to figure out how to ...