Understanding which page is being rendered through _app.js in React/Next.js is crucial for seamless navigation and

Currently, I am working on rendering my web navigation and footer on my _app.js file. My goal is to dynamically adjust the style of the navigation and footer based on the specific page being accessed. Initially, I considered placing the navigation and footer on individual pages, but I'm not sure if that's the most efficient approach.

Is there a way for me to determine the current page being accessed within _app.js?

For example:

pages/index.js
pages/profile.js

In my _app.js file, I aim to modify the styling of both the navigation and footer depending on the page that is being accessed.

Answer №1

Utilize the useRouter hook and access the asPath attribute.

import { useRouter } from "next/router";

const currentPath = useRouter().asPath;

You can utilize this value to dynamically adjust the content within the pages/_app.tsx file based on the page being accessed.

Answer №2

To customize the navigation and footer styles in Next.js based on Router.pathname, you can implement the following approach:

const getFirstPathName = pathname => pathname.split("/")[1]
export default class CustomStyle extends React.Component {
  static async getInitialProps ({ pathname, query }) {
    switch(getFirstPathName(pathname)) {
       case "":
       case "index": // style nav and footer for index.js
         break;
       case "profile": // style nav and footer for profile.js
         break;
       default: // handle default styling 
         break;
    }
  }
}

You can refer to this Pull Request for additional details: Add pathname and query to the argument of getInitialProps


UPDATE

In your situation, I recommend utilizing Redux to store the current URL at a higher component level. In the _app.js, you can then access this information to manage the navigation and footer styles accordingly. Here's an example:

Within the Component:

const ConnectedComponent = connect(null, dispatch => ({
   changeCurrentUrl: () => dispatch({ 
       type: "CHANGE_CURRENT_URL", payload: getFirstPathName(Router.pathname)
   })
}))
componentWillMount() {
   if (process.browser) { // ensure it is Client-side rendering in Next.js
       this.props.changeCurrentUrl()
   }
}

Within the Reducer:

export default {
   currentUrl: (state = "", action) => {
      if (action.type === "CHANGE_CURRENT_URL") {
          state = action.payload;
      }
      return state;
   }
}

In app.js // ensure connection to Redux is established here

componentWillMount() {
   const { currentUrl } = this.props
   // adjust navigation and footer styles based on the URL here
}

Answer №3

Utilize the document parameter.

const [website, setWebsite] = useState('')

useEffect(() => {
  setWebsite(document.URL)
}, [document.URL])

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

Wordpress articles refuse to appear side by side

I've been at it for hours now, trying to solve this issue with no luck. I have a Wordpress loop on my homepage that displays post thumbnails vertically, but I want them to appear in sets of three images before starting a new line. Here's the cod ...

designing a presentation with customizable durations for each slide

I am trying to implement a slideshow using the slides.js jquery plugin and I have a specific requirement for the duration of each slide. My goal is to have the first slide, which contains an embedded video, display for 7 seconds, while the subsequent slid ...

Is it possible to activate the nearby dropdown based on the user's selection?

On my html webpage, I have a form that consists of three dropdown menus each with different options: The first dropdown (A) includes choices from 1 to 6, as well as 'not set'. The second dropdown (B) allows selections from 1 to 7, and also has ...

Angular.js and DAO design pattern

Admitting my newness to Angular.js and lack of experience with frameworks like Backbone or Knockout, I am venturing into building an application that interacts with a server using a RESTful API. After delving deep into the angular documentation and blog po ...

Utilizing JSON data as a variable for handling in a Handlebars view within a Node.js/Express application

I am currently seeking a solution to display a view that includes a variable with data fetched from an API. My technology stack involves express, handlebars, and request. Here is the code for the web server's router: const express = require('ex ...

The desired hover effect on the navigation bar is not functioning properly

I have successfully created a hover effect for my navigation bar and the list inside it. However, I am facing an issue where the box shadow effect is only appearing in a small area when hovered (see image below). My goal is to extend the shadow effect to ...

Why is the outline buttons class only displaying gray colors for me?

I'm having trouble with the outline buttons class (btn btn-outline-primary) in Bootstrap. For some reason, all the buttons appear gray instead of colored as they should. Here's an example of how the buttons should look: https://ibb.co/ChKf83y, bu ...

Is it possible to convert xaml to html in a silverlight newsletter?

Currently, I am working on a project that involves creating a webpage where my admin can send emails directly through the website. To achieve this functionality, I have implemented a code snippet to send emails to all subscribers. foreach (Subscription pe ...

What is the best way to embed sections of one HTML page into another page?

Is there a method I can use to embed sections of one webpage within another webpage? The dilemma arises from the fact that the second page has a distinct style compared to my main page. Is it feasible to apply the alternate style solely to specific content ...

Interactive 3D model movable within designated area | R3F

I am currently facing a challenge in limiting the drag area of my 3D models to the floor within my FinalRoom.glb model. After converting it to tsx using gltfjsx, I obtained the following code: import * as THREE from "three"; import React, { useRe ...

Pressing a button to input a decimal in a calculator

I am encountering an issue with inputting decimals in my JavaScript. I have a function that checks if the output is Not a Number (NaN). If it is, I want it to output a decimal instead. I attempted to add another conditional statement like this: var opera ...

Enhancing the performance of a node.js Falcor router connecting a traditional REST API data source with a Falcor client

In my current setup, I have a traditional REST API that provides data in the following format: List of Users - GET /users.json users: [ {id: 0, name: "John Smith"}, ... ] User Details by Id - GET /users/0.json user: { id: 0, name: "Joh ...

Arrange an array of objects by making a nested API call in Angular

My task involves sorting an array of objects based on the response from the first API call in ascending order. The initial API call returns a list of arrays which will be used for the subsequent API call. The first API call fetches something like this: [0 ...

Changing the background color of .pane and .view elements in an Ionic web application using JavaScript

Looking to modify the background-color of two css selectors, .pane and .view, that are located within the ionic.css file. Despite multiple attempts to do so using JavaScript directly in the index.html file, the changes are not reflected. The code snippet ...

Difficulty with Bootstrap 4 mobile navbar dropdown feature

<div class="baslik baslik1 baslik2 "> <nav class="navbar bg-light navbar-light navbar-expand-sm sticky-top "> <a href="./index.html" class="navbar-brand"><img src="img/512x512logo.png" ...

I updated the version to 13, and as a result, the process of building the storybook has encountered a roadblock

After upgrading next.js to version 13, the storybook build is failing. Here's a snippet from the storybook: I'm stuck on how to fix this issue and would appreciate any help in resolving it. error ERR! => Failed to build the preview ERR! M ...

Determining the existence of a file on a different domain using JavaScript

One of the key tasks I need to achieve from JavaScript on my HTML page is checking for the existence of specific files: http://www.example.com/media/files/file1.mp3 // exists http://www.example.com/media/files/file2.mp3 // doesn't exist Keep in mi ...

Unpacking a props object results in an undefined value

I've been struggling to set up a data-grid in react because I'm facing issues with accessing the data from my props. Whenever I try to access or destructure the prop, it shows up as "undefined" in my console. This problem only arises when the p ...

Tips on changing font color within an email body in Outlook using a C#.NET Windows application

While working on a c#.net windows application, I encountered an issue with setting font color for specific lines in the email body when sending mail to Outlook. Despite trying various methods, I was unable to find a solution. Below is a snippet of my code: ...

Utilize a single submit button to navigate through multiple pages dynamically using JavaScript

I would like to navigate to different rooms with just one button using JavaScript. For instance, there are three rooms: "Kitchen, Toilet, and Bedroom". How can I utilize JS to enter any of these rooms based on my selection? If I input "kitchen" in the text ...