show/hide components based on route
Unanswered
Mini Satin posted this in #help-forum
Mini SatinOP
I have a common header/ sidebar and footer component that needs to be on all pages except login, 404 (wrong/missing routes). Currently I have these components in the layout and avoid rendering them for login page, but for undefined routes (404 page) i don't know how to go about it?
I want to avoid adding all of the defined routes and whitelisting them for these components? any better approach?
I want to avoid adding all of the defined routes and whitelisting them for these components? any better approach?
7 Replies
how about exporting a provider and importing it inside the global Layout file.
in the provider, you can do something like this:
then wrap your Layout with the provider
in the provider, you can do something like this:
'use client' // creating a provider because we the Layout component cannot be marked as a client component
import {usePathname} from 'next/navigation';
import {Header, Footer} from '@/components';
export const LayoutProvider = ({ children }) => {
const pathname = usePathname();
return (
<>
{pathname !== "/404" && <Header />
{children}
{pathname !== "/404" && <Footer />
</>
)
};then wrap your Layout with the provider
import {LayoutProvider} from '@/context';
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<LayoutProvider>
{children}
</LayoutProvider>
</body>
</html>
)
}Mini SatinOP
i was able to achieve this without using the route check with routeGroups. Created seeprate layouts for each routegroups
thank you @Dayo
oh okay. how did that work with the 404 page?
Mini SatinOP
so 404 will be in the root layout, all the headers, sidebar and footers will be added to the layout within my main app (home) route group.
this is my folder structure
ah i see. very nice!