EDIT:
I’ve found what was messing up. I was wrapping my subpages return elements into main layout component. My bad. Thanks for answers guys.
so I have a problem with the Link component. I have an app directory with layout.tsx, page.tsx, and directory /about. When I’m using Link in page.tsx to go to /about it works fine, layout is applied. In about I have client component. In that component when I use Link with href=’/’ to go back to the main page components from page.tsx are applied but layout.tsx is not. I’ve added console logs to the layout and page. When I’m trying to go back from /about none of the console logs is displayed in the terminal. Here is the code:
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 ? 'Zapisz' : 'Dodaj'}</div>
<Link href='/'><div className={styles.CancelButton}>{changesMade ? 'Anuluj' : 'Wróć'}</div></Link>
</div>
</div>
I’ve tried using <a>
and it worked but I want to know why going back with Link isn’t working
1
It maybe because of hydration issue. Since layout render on server and Link is inside a client component.
Client components sometimes cause unpredictable issues with the nextjs App router layout
you can try navigating with 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 ? 'Zapisz' : 'Dodaj'}</div>
<div className={styles.CancelButton} onClick={() => router.push('/')}>
{changesMade ? 'Anuluj' : 'Wróć'}
</div>
</div>
);
};
1