Using Next.js with the Link component in a client-side component to navigate back to a different page does not properly display the

UPDATE: After some investigation, I finally identified the issue. It turns out that I mistakenly wrapped my subpages return elements into the main layout component. Thank you all for your input!

Currently, I am facing a challenge with the Link component in my application. Within my app directory, I have files named layout.tsx, page.tsx, and a directory called /about. When I utilize Link in page.tsx to navigate to /about, everything works smoothly as the layout is applied. However, within the 'about' section, there is a client component. In this component, when I use Link with href='/' to return to the main page, components from page.tsx are applied but not the layout.tsx. To debug this issue, I added console logs to both the layout and page. Strangely, none of these logs appear in the terminal when attempting to go back from /about. Here is the relevant code snippet: layout.tsx:

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  console.log('layout')
  return (
    <html lang="en">
      <head></head>
      <body className={styles.main}>
          <VideoBackground />
          {children}
      </body>
    </html>
  )
}

page.tsx:

export default async function Page() {
  const plants = await getPlants()
  console.log('plants page')
  return (
        <PlantsGrid 
          plants={plants}
        />
  );
}

and link in client component:

<div className={styles.RightContent}>
          <div className={styles.Button} onClick={props.update ? updatePlant : sendNewPlant}>{props.update ? 'Save' : 'Add'}</div>
          <Link href='/'><div className={styles.CancelButton}>{changesMade ? 'Cancel' : 'Go Back'}</div></Link>
        </div>
      </div>

I did try using <a> and that seemed to work fine. However, I am curious about why going back with Link isn't functioning properly.

Answer №1

It could be related to a hydration issue. The layout renders on the server and the Link is inside a client component, which can sometimes cause unpredictable issues with the nextjs App router layout.

You may want to consider navigating using the useRouter() hook instead of Link

import {useRouter} from 'next/navigation';

     const ClientComponent = () => {
     
        const router = useRouter();
       
        return (
           <div className={styles.RightContent}>
            <div className={styles.Button} onClick={props.update ? updatePlant : 
              sendNewPlant}>{props.update ? 'Save' : 'Add'}</div>
            <div className={styles.CancelButton} onClick={() => router.push('/')}>
               {changesMade ? 'Cancel' : 'Go back'}
            </div>
           </div> 
         );
    };

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

Scrolling through a list of objects in a React component to display a vertical lineup of items including the name and logo

Currently, I am working on developing a vertical scrolling ticker/item list that showcases both the name and logo of each item within an array. Initially, I had set up a scrolling ticker solely with names using webkit animations on styled components. Howev ...

Ways to verify if a string is a number without using isNaN and with specified criteria

I am trying to determine if a string represents a valid number without relying on the isNaN function. The reason for this is that I need to be able to accept the ',' character, which isNaN ignores. Additionally, I do not want to allow negative nu ...

The implementation of useState delays the application of dynamic styling

I'm currently developing a Next.js application. Here is the code snippet from my client-side component: const [view, setView] = useState<string[]>(["all"]); const story = stories?.holidays; const joke = stories?.jokes; const idiom = s ...

Instructions on keeping a numerical counter at its current value for all site visitors

Recently, I integrated a number counter into my website. However, I am facing an issue where the count resets to zero whenever a new visitor accesses the site. I'd like the count to remain persistent and update based on the previous count. For instanc ...

How to assign a locally created array in a function to a globally defined array in JavaScript

Whenever I try to assign arrays, a problem arises: var arr = [ {'id': 1, 'size': 'large' }, {'id':4, 'size': 'small'} ]; function adjust(a){ var result=[{'id': 1, 'si ...

Having trouble replicating a function that works perfectly in my browser using the latest release of Selenium

This is my initial inquiry and I am hoping to receive some assistance. After extensive research on Selenium WebDriver actions, I have been unable to find a solution. My objective is to test whether I can successfully add a new class to the element that I ...

Linking a pair of checkboxes

I am dealing with two checkboxes on my website. <input class="checkbox1" type="checkbox" name='1' id="example1" value="example1"/> and <input class="checkbox2" type="checkbox" name='2' id="example2" value="example2"/> I ...

javascript has been overrunning with an abundance of attached comments loops

I've been encountering an issue where I am unable to properly link my comments to the message id. Below is what I have attempted: Routes file: router.get('/home', function(req, res){ if(req.cookies.user_id){ knex.raw(`SELECT * ...

Issues arise when attempting to call a panel on multiple pages within jQuery Mobile

I am encountering an issue with my HTML document that has multiple pages utilizing jQuery Mobile's data-role="page". Specifically, I am attempting to trigger a panel on the second page and running into the following error: Error: cannot read proper ...

Troubleshooting problem with updating a record in the MongoDB using Node.js and

Currently, I am developing a REST API using Node, Express, and MongoDB. I have successfully implemented fetch, create, and delete functions but facing issues with the update function. Every time I attempt to test it using Postman, the code hangs, the serve ...

Implementing auto-complete functionality using two keys in Material UI and React

My goal is to enable autocomplete for input when searching with values like title and year. Strangely, the autocomplete feature only works when I search with title. Searching with year does not yield any options. Sample code export default function ComboB ...

When uploading an image file using HTTP post, extra characters are added to the beginning of the file

I'm attempting to transfer a basic image file to a lambda function. Once the data reaches the function, I need to convert it into a buffer and then make alterations to it. Presently, when the data is received, there are numerous characters attached at ...

Uncovering "camouflaged" HTML using Jsoup

Seeking to access HTML data that is not initially visible in the source document but can be revealed through tools like "inspect element" in Google Chrome. Here's an example page: There are div elements with assignment data for U.S. Patent No. 9,000 ...

Alerts warning against the utilization of the await term in an asynchronous function

I encountered some error messages while working on my NextJS API route. Here is a simplified version of the code: // /app/api/tacos/route.js export async function GET(request) { const data = [{name: 'a'}, {name: 'b'}, {name: 'c&a ...

Exploring MongoDB through proxyquire

To simulate a MongoDB dependency using proxyquire in my testing scenario, I have the following code snippet: var proxyquire = require('proxyquire'); var controller = path.resolve('.path/to/controller/file.js'); inside the before each ...

tips on displaying information in a vertical tab orientation

I'm struggling to figure out how to loop inside the <TabPanel> in order to render data using React vertical tabs. I've provided the code I've tried and the data coming from an API. Check out the codesandbox at https://codesandbox.io/s/ ...

Utilizing PHP for a server-side backup in case the CDN is inaccessible

Looking to simulate some server-side functionality: <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript"> if (typeof jQuery == 'undefined&apo ...

Struggling with implementing middleware stacking in the router of my next14 app for i18n and authentication

Currently working on a project called next14. I have successfully set up middleware for i18 and am now attempting to add a second middleware for authentication using auth.js (next-auth). I believe both middlewares are functioning properly, but it seems li ...

Add Firebase Data to Dropdown

Utilizing Vuetify to build a dropdown has been an interesting challenge for me. While I can successfully select a value and store it in the firebase database, I'm facing difficulties when it comes to repopulating the dropdown after page refresh. Belo ...

Ways to transfer data from one page to another using AngularJS

Hey everyone, I could really use some assistance with AngularJs. My code is quite lengthy, so I have uploaded a document file for you to review. The code snippet below shows my authentication process for email and password. The customerlogin() method retur ...