Modifying a property in a nested layout through a page in Next.js 13

Currently, I am facing a challenge in updating the page title within a nested layout structure.

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 am struggling to find a proper method to pass the PAGE_TITLE from sub pages to the header in layout.tsx. Currently, I am resorting to checking the URL pathname of each page and updating the h2 element 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 understand that this is not the most efficient approach. I would greatly appreciate it if someone could guide me on how to resolve this using the correct methodology.

Answer №1

If you're looking to enhance flexibility and eliminate the need to rely on URL pathname, consider utilizing React Context.

To begin, establish a new context dedicated to storing the current page title. Adjust the DocsLayout component to supply the context value, then proceed to update the subpages for consumption and setting of this value.

Setting Up the Page Title Context:

// Begin by creating a new file, for instance, PageTitleContext.js
import React from 'react';

export const PageTitleContext = React.createContext({
  pageTitle: '', // Initial value
  setPageTitle: () => {} // Placeholder function
});

Enhancing DocsLayout for Context Provision:

// app/docs/layout.tsx
import React, { useState } from 'react';
import { PageTitleContext } from './PageTitleContext'; // Import the created 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>
  );
};

Utilizing Context in Subpages:

// app/docs/linux/page.tsx
import React, { useContext, useEffect } from 'react';
import { PageTitleContext } from '../PageTitleContext'; // Import the defined context

export const Linux = () => {
  const { setPageTitle } = useContext(PageTitleContext);

  useEffect(() => {
    setPageTitle("Linux");
  }, [setPageTitle]);

  return (
    <div>Content related to Linux</div>
  );
};

// Similar adaptations can be applied in app/docs/macos/page.tsx

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

Using create-react-app with TypeScript for server-side rendering

My current project is built with create-react-app using typescript (tsx files). I'm now interested in implementing SSR for the project, but I'm not exactly sure where to begin. In the past, I've successfully implemented SSR with typescript ...

I am experiencing an issue where emojis are not displaying properly on Facebook, Instagram, and LinkedIn when I share posts from my

I've developed a unique social media management application that enables users to automatically post on their social profiles using the Facebook, Instagram, and LinkedIn APIs. Everything is functioning well, except for one issue - my Emojis are not di ...

Using checkboxes for filtering in a React application

Here are the data sets I am working with: const dataSet = [ { id: 1, title: 'object1', published: true, }, { id: 2, title: 'object2', published: true, }, { id: 3, title: 'object3', ...

React Hooks state consistently lags behind

I am facing an issue with resetting the page to 1. When I use handleSearchClick function and call setPage(1), it seems to reset one click late. Therefore, after the second click, the page resets to 1. This is my current code: const [page, setPage] = R ...

"React - encountering issues with state being undefined when passing child state up through parent components

I am currently navigating the world of react and have encountered a hurdle. I find myself facing difficulties in updating the parent component based on changes in the child state. I was able to pass the child state to the parent by linking the child's ...

Translate Firestore value updates into a TypeScript object

Here are the interfaces I'm working with: interface Item { data: string } interface Test { item: Item url: string } In Firestore, my data is stored in the following format: Collection Tests id: { item: { data: " ...

Cookie revealed in cookies section, vanishes within a moment [NextJS & cookies-next]

I'm utilizing cookies-next library to create a cookie in my NextJS application, following the documentation provided (pages router, client side): const cookieOptions = { expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 399), // set to expire aft ...

Need help tackling this issue: getting the error message "Route.post() is asking for a callback function, but received [object Undefined]

I am currently working on implementing a new contactUs page in my project that includes a form to store data in a mongoDB collection. However, after setting up all the controller and route files and launching the app, I encountered an error that I'm u ...

Deactivating Touchable Opacity Sounds in React Native

Currently, I am in the process of developing an application, utilizing TouchableOpacity instead of a button. I am looking to disable the auditory feedback that occurs when the TouchableOpacity component is pressed. <TouchableOpacity activeOpacity={1} to ...

Exploring the process of dynamically incorporating headers into requests within react-admin

Currently utilizing react-admin with a data provider of simpleRestProvider. I am in need of a solution to dynamically add headers to requests based on user interactions. Is there a way to achieve this? Appreciate any assistance. Thank you! ...

What is the best way to specify a type for an object without altering its underlying implicit type?

Suppose we have a scenario where an interface/type is defined as follows: interface ITest { abc: string[] } and then it is assigned to an object like this: const obj: ITest = { abc: ["x", "y", "z"] } We then attempt to create a type based on the valu ...

Alter the color of Material UI Raised Button when it is hovered over

I am trying to change the background color of a raised button on hover in Material UI. I attempted the following, but it did not work. Is there a way to modify the background color in Material UI for a raised button? Example.JS <RaisedButton ...

implementing GraphQL lists in mutations using Apollo in a React JS application

My current situation involves a mutation that looks like this: orderAdd(products: [ProductInput],restaurant: RestaurantInput) implemented in graphql, and now I want to pass parameters to it using Apollo in react js as shown below: mutation orderAdd ($ ...

React and Express application facing issue with JSX rendering restriction

I've been delving into the world of web app development with Express, but I'm struggling to grasp how it transmits data to the client side and what its main function is. My understanding is that Express is responsible for sending data to the clie ...

What is the best way to integrate and utilize the jsgrid library in a React project?

I've encountered an issue with the jsgrid library while trying to integrate it into a React project. I followed the instructions on npmjs and included the necessary libraries in the project. Here is my code snippet: index.html <!DOCTYPE html> ...

Sending the `onChange` prop from a parent component to a group of child elements

If I have a setup with a component like the example below, how can I efficiently pass the onChange prop to every instance of DropdownItem? Rather than adding it directly to each DropdownItem, which could become repetitive. <Dropdown onChange={(select ...

The custom error page in NextJS is failing to display

In my custom pages/404.ts file, I have coded the following: export default function NotFound() { return <h1>404 - Page Not Found</h1> } Additionally, there is another page that displays a 404 error when the organization is null: import Error ...

Solving filtering issues within React using a combination of conditions

I've been struggling to selectively remove an item from my array. The current filter I'm using is removing too much. Here is the array in question: [ { "domain": "domain1.com", "slug": "moni ...

Having trouble calling a parent method from a child component in ReactJS

Within my parent container, there is a validation function that checks the input provided by users. The parent container includes a child component in its rendering. render() { return ( <div> <Child valu ...

Error encountered in the React task manager application: TestingLibraryElementError - Element with [data-testid="add-task-form"] could not be located

I've been working on testing my basic task manager app built with React. Below are the components and test files: Component (AddTask.js) import React, { useState } from 'react'; function AddTask({ addTask }) { const [task, setTask] = use ...