Next.js Discord

Discord Forum

How to Set a Value in the Layout Based on the Current Page

Unanswered
Jersey Wooly posted this in #help-forum
Open in Discord
Jersey WoolyOP
I have a PageHeading component that, because of a rush job, gets its heading text from a "global" variable. This is already wrong, because that variable is for read only config values set on app startup, where the page heading is very variable. It takes a props object of type PageHeadingProps with propertiesheadingLevel, which determines the level of a heading element, i.e. H1, H2 H3 etc. and headingText, which carries the text for that heading element.

This is how I hastily included this heading component in the route layout for the Product Category page, (app/(sidebar)/layout.tsx and app/(sidebar)/category/[slug]/page.tsx) back when I only had one page that needed a heading.

layout.tsx:
    const pvals: PageHeadingProps = { headingLevel: appConfig.pageHeadingLevel, headingText: appConfig.pageHeadingText };
    return (
        <div id="main" className="relative mr-auto ml-auto pt-1 pb-12">
            <PageHeading {...pvals} />

Now the heading text is fixed in my appConfig object, which even if I didn't want it to be readonly, I can't change its properties in the page that . When I try like this, in the category/[slug]/page.tsx page
appConfig.pageHeadingText = `Product Category: ${catName}`;

I get the error:
Modifying a variable defined outside a component or hook is not allowed. Consider using an effect.
Now using a global variable is certainly not the right way to do this, and while I believe if I look into React's effects, I could solve this, hell I could even solve it with a jquery type script, but there is probably a more proper way of doing this. I could include the PageHeading component in every page, but it's common to about 90% of the pages. Everything except the heading text, which needs to change per page.

I am busy looking into React's Context right now, it looks like the preferred way of doing things.

1 Reply

Jersey WoolyOP
It looks like React contexts are the way to do this kind of thing.