Issue
I'm trying to update the page title found in a nested layout.
app/docs/layout.tsx:
export const DocsLayout = ({children}:{children: React.ReactNode}) => {
return (
<>
<header>
<h2>Documentation - {/* platform goes here */}</h2>
</header>
<div>{children}</div>
</>
)
}
app/docs/linux/page.tsx:
export const Linux = () => {
const PAGE_TITLE = "Linux";
return (
<div>Linux content</div>
)
}
app/docs/macos/page.tsx:
export const MacOs = () => {
const PAGE_TITLE = "MacOS";
return (
<div>MacOS content</div>
)
}
I have no idea how to pass the PAGE_TITLE
from sub pages to the header in layout.tsx
so I have ended up using the URL pathname to check each page and update the h2
accordingly.
app/docs/layout.tsx:
export const DocsLayout = ({children}:{children: React.ReactNode}) => {
const pathname = usePathname();
const [platform, setPlatform] = useState("Linux");
if (pathname === "/docs/linux") {
setPlatform("Linux");
}
else if (pathname === "/docs/macos") {
setPlatform("MacOS");
}
return (
<>
<header>
<h2>Documentation - {platform}</h2>
</header>
<div>{children}</div>
</>
)
}
I know this is not the ideal approach. Can someone help me fix this using the "right" way?
Solution
You can use React Context. This will give you more flexibility and avoid relying on URL pathname.
Define a new context that will hold the current page title. Modify DocsLayout
component to provide the context value. Then update the subpages to consume and set the context value.
Create the Page Title Context :
// Create a new file, e.g., PageTitleContext.js
import React from 'react';
export const PageTitleContext = React.createContext({
pageTitle: '', // Initial value
setPageTitle: () => {} // Placeholder function
});
Update DocsLayout to Provide Context :
// app/docs/layout.tsx
import React, { useState } from 'react';
import { PageTitleContext } from './PageTitleContext'; // Import the context
export const DocsLayout = ({children}:{children: React.ReactNode}) => {
const [pageTitle, setPageTitle] = useState('');
return (
<PageTitleContext.Provider value={{ pageTitle, setPageTitle }}>
<header>
<h2>Documentation - {pageTitle}</h2>
</header>
<div>{children}</div>
</PageTitleContext.Provider>
);
};
Consume Context in Subpages :
// app/docs/linux/page.tsx
import React, { useContext, useEffect } from 'react';
import { PageTitleContext } from '../PageTitleContext'; // Import the context
export const Linux = () => {
const { setPageTitle } = useContext(PageTitleContext);
useEffect(() => {
setPageTitle("Linux");
}, [setPageTitle]);
return (
<div>Linux content</div>
);
};
// Similar changes will be made in app/docs/macos/page.tsx
Answered By - Batman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.