What is the best way to share an HTML element across multiple pages in Next.js?

I am in the process of developing a website that features a table of contents with links on the left side, content sections in the middle, and an overview on the right. For a visual representation of the general concept, please visit: https://i.sstatic.net/1uf4P.png

Currently, all code is contained within one function:

import React from 'react';
import styles from '../styles/Home.module.css'
import table_of_contents from './test.js'

export default function Home() {
  return (
    <div className={styles.grid_container}>
      ... (code omitted for brevity)
  )
}

I am seeking to make the

<div className={styles.left_pane}>...</div>
section reusable as it needs to be rendered for each link in the document for navigation purposes. However, due to my limited understanding of Nextjs/js/CSS, I am uncertain about the optimal way to structure this.

In an attempt to achieve reusability, I created another JavaScript file and defined a new function:

import React from 'react';
import styles from '../styles/Home.module.css'

export default function table_of_contents () {
  return (the div here)

Unfortunately, I encountered difficulties getting it to render properly.

Any advice on how I can accomplish this effectively?

Answer №1

To optimize the organization of your code, I recommend placing the "navbar" in a separate file within a folder named components. Create a new component called Layout and include the navbar along with any other children it will interact with. Here is an example snippet of how you can structure this:

import NavBar from "./NavBar";

const Layout = ({ children }) => {
  return (
    <div>
      <NavBar />
      {children}
    </div>
  );
};

export default Layout;

Next, navigate to your _app.js file and enclose your layout around all the content. Modify your code as follows:

import "../styles/globals.css";
import Layout from "../components/Layout";

function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  );
}

export default MyApp;

This marks my debut post on StackOverflow, so forgive me if the explanation is not crystal clear. Feel free to ask for further clarification.

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

Avoiding unlimited re-renders when using useEffect() in React - Tips and Strategies

As a new developer, I recently built a chat application using socket io. In my code, I have the useEffect hook set to only change when the socket changes. However, I also have setMessage within the body of useEffect(), with socket as a dependency. Unfortun ...

PHP echo functions are not functioning properly in a dynamically loaded PHP page through jQuery's .load function

Within my WordPress installation, I have index.php and desktop.php files. The goal is to load desktop.php into #tLoad only if the browser window width is greater than 800px. While this works fine, I am encountering issues when trying to use PHP functions a ...

Using Angular 2 to select with default value from a separate model

Is there a way to set the default value or link to another model while utilizing NgFor on a different model? The model intended for binding is as follows: "Bookings": {"dates": [{"date":"3-10-2016","slot":"Full"}, {"date":"4-10-2016","slot":"Full"}, {"da ...

Invalid element type. The promise returned is for undefined value. The element type for lazy loading must resolve to a class or function

I'm currently using NextJS v14 alongside MUI v5. On my home page, I have a news component that's causing an error when I try to turn it into a server component for fetching data. Despite successfully logging the data in the terminal, the issue ar ...

Troubleshooting challenges with a React web application and resolving the issues

Recently, I stumbled upon a React web application from GitHub that caught my interest. I followed the instructions and ran the code using "npm start" in the terminal before accessing it at http://localhost:8080/webpack-dev-server/. However, I encountered a ...

Font sizes for inline elements can be customized with gaps

Having trouble with setting font-size styles for inline elements, causing unexpected gaps to appear. Despite finding related questions on this issue, I have yet to discover a solution that fits my specific case. Here is the code in question: <!docty ...

What causes an error when jqXHR.abort() is invoked in the beforeSend function?

Attempting to interrupt ajax call with beforeSend in case of a specific condition. Upon executing jqXHR.abort() or return false, I encounter the following error message: TypeError: $.ajax(...).fail is not a function .fail(function (jqXHR, textStatus, er ...

Adjust the sliders according to the current time

I am looking to display different sliders based on the time of day. For instance, 'slider set 1' from 0-9am, 'slider set 2' from 9am-12pm, and so forth. I am new to java script and need assistance in solving this challenge. Below is the ...

Guide on extracting part of a string in JavaScript from a specific starting point to a designated character

Currently working on a JavaScript project where I am in need of extracting words enclosed within two brackets. For example: [Green]- Amazon I specifically require the word "Green" from within the brackets. Using indexOf() won't work as there could ...

How can you incorporate TypeScript's dictionary type within a Mongoose schema?

When using TypeScript, the dictionary type format is: { [key: string]: string; } However, when I try to define a custom schema in mongoose, it doesn't work as expected. const users = new Schema({ [key: string]: String, }); I also attempted t ...

Problems with Bootstrap affix scrolling in Internet Explorer and Firefox

I'm encountering an issue with the sidebar on my website. I've implemented Bootstrap affix to keep it fixed until the end of the page, where it should move up along with the rest of the content at a specific point... Everything seems to be worki ...

When you try to click outside of react-select, the dropdown doesn't

I've been working on customizing react-select and encountered some issues. Specifically, after modifying the ValueContainer and SelectContainer components, I noticed that the dropdown doesn't close when clicking outside of it after selecting a va ...

The setInterval function continues to execute endlessly even after each interval is three months

I need to remove all expired OTP records every three months. In the file /sheduled-tasks/OTPRecords.js const prisma = require("../services/prisma"); const THREE_MONTHS = 1000 * 60 * 60 * 24 * 90; async function deleteExpiredOTPRecords() { ...

Preventing the dropdown options from appearing in Angular when clearing the input field

In a reusable component, I implemented some simple logic to clear the value of a select input when the 'x' button is clicked. select.component.ts @Input() selectFormControlName: string; @Input() selectAbstractControl: AbstractControl; ... ...

When utilizing Rx.Observable with the pausable feature, the subscribe function is not executed

Note: In my current project, I am utilizing TypeScript along with RxJS version 2.5.3. My objective is to track idle click times on a screen for a duration of 5 seconds. var noClickStream = Rx.Observable.fromEvent<MouseEvent>($window.document, &apos ...

The Rails application is loading JavaScript three times

I am encountering an issue with my ajax function where it is being triggered multiple times upon click instead of just once. $(document).on('click', '.newGameItem', function() { console.log('start click event'); var a ...

Angular appends "string:" in front of value when using ng-options

In my HTML, I have a ng-options list set up with a select element like this: <select required="required" ng-model="vm.selectedOption" ng-options="item.name as item.label for item in vm.options"> <option value="">Select an opti ...

The right structure of folders and dynamic routing in Next.js

I have a Link that passes a href in my code snippet: { name: "Action", cell: (row) => ( <div className="flex items-center space-x-5"> <Link href={`/members/${row.id}/edit`}>Edit</Link&g ...

Transforming content dynamically

I am currently working on a single-page website that features a comprehensive product catalog. Here are the key elements I'm focusing on: A one-page website layout, complete with header, content, and footer (developed using HTML5/CSS3) Dynamic cont ...

Streamline email error management within nested middleware functions

I have implemented an express route to handle password resets, which includes finding the user and performing some error handling. However, I am now faced with the challenge of adding additional error handling within a nested function, and I am uncertain a ...