How can you conceal the navigation and footer components on a 404 page using Next.js?

import Footer from "./Footer";
import Navigation from "./Navigation";
import { useRouter } from "next/router";

function CustomLayout({ children }) {
  const router = useRouter();
  return (
    <>
      {router.pathname !== "/*" && <Navigation />}
      {/* {router.pathname !== "*" && <Navigation />} */}
      <main className="main-content">{children}</main>
      {router.pathname !== "/*" && <Footer />}
      {/* {router.pathname !== "*" && <Footer />} */}
    </>

    );
}

export default CustomLayout;

It seems like the methods with an asterisk are not functioning properly. Any suggestions on how to fix this issue? Thank you in advance and best regards to everyone! ;-)

Answer №1

If you do not have a customized 404 page, the default value of router.pathname is _error, so the code snippet below should suffice:

{router.pathname !== "/_error" && <Navigation />}

If you are using a custom 404 page (located at 404.js inside the /pages directory), then the value of router.pathname will be /404.

If you decide to reuse the built-in error page, the value of router.pathname within your page or component will match the current page path.
For example:

import Error from 'next/error'

const MyPage = ({isError = true})=>{
    // The page path would be something like pages/mypage
    return isError ?  <Error statusCode={"404"} /> : <p>My page </p>
}

export default MyPage 

In this scenario, neither of the methods mentioned above will work properly.
However, I do not recommend utilizing this approach.

Answer №2

I made the decision to include this code snippet here for the benefit of others who may come across a similar issue. Specifically, in scenarios where a custom 404 page is being used, the solution can be implemented as follows:

import Footer from "./Footer";
import Navigation from "./Navigation";
import { useRouter } from "next/router";

function Layout({ children }) {
  const router = useRouter();
  return (
    <>
      {router.pathname !== "/404" && <Navigation />}
      <main className="main-content">{children}</main>
      {router.pathname !== "/404" && <Footer />}
    </>
  );
}

export default Layout;

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

Is there a way to consistently apply default props to a styled component?

Currently, I am working with React, Material UI, and Styled Components. My goal is to create a personalized Input field where the size='small' is always passed as a prop to my component. To clarify, if the user neglects to include the size attri ...

I am having trouble displaying SASS styles in the browser after running webpack with node

In my current project for an online course, I am utilizing sass to style everything. The compilation process completes successfully without any errors, but unfortunately, the browser does not display any of the styles. The styles folder contains five file ...

Hitting a button causes Ajax.load to malfunction

Struggling to make ajax.load method work when clicking a button. The concept is simple: swap out the content of a div with something else using ajax.load. However, despite hours of research, I have yet to find a solution. Pressing the button does nothing. ...

The smooth shading in Three.js is giving off a flat appearance

When loading .stl files, I'm using MeshStandardMaterial without adjusting the flatShading property since it is set to false by default. https://i.sstatic.net/zbCiR.png The outcome appears rather dull to me. Even when attempting to toggle flatShading ...

Include an extra "array" in the complete AJAX POST data when submitting through x-editable

Struggling to include an array of objects in the post data for a group of bootstrap x-editable on my JSP page. The data is retrieved from a table and an array of objects is constructed. This array needs to be appended to the list of other values posted by ...

Using Three.js to seamlessly transition from one Panorama Cube to another with a smooth zoom-in effect

As a newcomer to Three.js, I am currently experimenting with an example featuring a set of 6 image cubes for a panorama effect. This allows users to pan, zoom in, and zoom out around the cubes. If you're interested, you can check out the example here ...

What is the code to convert data to base64 in Javascript when it is not a string?

I am in the process of transferring functionality from an Objective-C iPhone application to a JavaScript iPhone application (using Appcelerator Titanium). In my Objective-C code, I have an NSData object that represents a specific token: //NSData object sh ...

The ng-repeat in the inner loop is excluding the initial element of my array and subsequently placing them in the final HTML tag

I am facing a challenge with converting a JSON array into HTML using angular's ng-repeat. The JSON structure I'm working with looks like: data:{ thing_one:[{ id:1, fields:[{ .... }] }, { id:2, fields:[{ .... ...

ModSecurity Action Causing AJAX Problem

An error is being triggered by the URL below with a message of "Modsecurity forbidden status code: 403". This URL is being returned from an AJAX call. like ? and active = ?&params='%ABCDE%'|1&element_id=hello If I remove %% from ABCDE ...

The functionality of Protovis JavaScript is not supported within a dropdownlist's onchange event

I encountered an issue where one block of code works fine on its own, but when combined with another block, only one of them functions properly. The problem arises when I try to invoke a method from a dropdownlist using the onchange event, especially afte ...

Encountering an issue while trying to set up a fresh react application

Issue encountered when trying to start a new React project ...

Angular log out function to automatically close pop-up windows

Within my application, there is a page where users can open a popup window. When the user clicks on logout, it should close the popup window. To achieve this, I have used a static variable to store the popup window reference in the Global.ts class. public ...

How to Enhance GraphQL Mutation OutputFields with a Function Generator

I'm encountering issues while trying to incorporate a function generator within a GraphQL mutation. The function generator is utilized to streamline the promise chain inside the mutation. Prior to refactoring the code, everything was functioning corr ...

Sending Emails with Next.js

Hey there, I've been working with nodemailer and Next.js, but I keep running into an issue when trying to add an image to my email. The error message I'm getting is: err: [Error: ENOENT: no such file or directory, open '/images/welcome.png&a ...

Tips on identifying HTML email input validation using JavaScript?

Just like when you can determine whether an input element with a required attribute was successfully validated, try using the following code: if($('input[type="email"]').val() && $('input[type="email"]').val().includes('@') & ...

How to Utilize findIndex to Validate the Presence of Elements in an Array of Objects using TypeScript

I need assistance in checking which properties from an array are present in another array of objects and which ones are not. My object structure is as follows: var tempObj=[{id: '1', color: 'red, blue, green', age: 27},{id: '2& ...

Is it feasible to conceal certain parameters within a URL using Angular UI Router?

Looking to pass two values to a new ui-view via parameters: item id list of objects However, I want the new view to display only the id in the browser URL and not the stringified array of objects: http://www.myapp.com/#/my-view/4 INSTEAD OF http://ww ...

The process of updating JSON data based on changes triggered by DOM events such as drag and drop

One challenge I am facing involves a Vue component used to render child components based on JSON data. The goal is to allow users to move and add components by dragging and dropping DOM elements on the page, using tools like jQuery draggable, droppable, an ...

Challenge with Angular *ngFor: Struggling to Access Previous Elements

In my angular and node application, I am using socket.io. When a user joins the room, they can see their username in the user list. If another user joins, the first user can see both usernames but the new user can only see their own. This pattern continues ...

Is a single f.select impacting another f.select in the same form? (undesired)

I am facing an issue where adding a new HTML element like: <%= f.date_select :date, { id: "date-select"} %> is impacting my existing collection select: <%= f.collection_select :id, Customer.where(business_id: current_c ...