Customizing page layout for pages wrapped with higher-order components in TypeScript

Looking to add a layout to my page similar to the one in this link:

layouts#per-page-layouts

The difference is that my page is wrapped with a HOC, so I tried applying getLayout to the higher order component itself like this:

PageWithAuth.getLayout

However, I encountered this error:

https://i.sstatic.net/VVtAR.jpg

The structure of the page is as follows:

function TestPage() {
  return {
    /** Your content */
  }
}

const PageWithAuth = withAuth(TestPage);

PageWithAuth.getLayout = function getLayout(page: ReactElement) {
  return (
      <Layout>{page}</Layout>
  )
}

export default PageWithAuth;

The _app.tsx file has the following setup:

type NextPageWithLayout = NextPage & {
  getLayout?: (page: ReactElement) => ReactNode
}

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout
}

export default function MyApp({ Component, pageProps }: AppPropsWithLayout) {
  // Use the layout defined at the page level, if available
  const getLayout = Component.getLayout ?? ((page) => page)

  return getLayout(<Component {...pageProps} />)
}

The HOC is defined as follows:

export function withAuth<P>(WrappedComponent: React.ComponentType<P>) {
  const ComponentWithAuth = (props: P) => {
    return <WrappedComponent {...props} />;
  };
  return ComponentWithAuth;
}

How can this issue be resolved?

Answer №1

To explicitly specify the return type of withAuth, you can define a new type WithAuthComponent<P> by extending React.FunctionComponent<P> and including the getLayout property.

type WithAuthComponent<P> = React.FunctionComponent<P> & {
    getLayout?: (page: React.ReactElement) => React.ReactNode
}

export function withAuth<P = {}>(WrappedComponent: React.ComponentType<P>): WithAuthComponent<P> {
    const ComponentWithAuth = (props: P) => {
        // Implement your authentication logic here
        return <WrappedComponent {...props} />;
    }
    return ComponentWithAuth
}

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

Obtain code coverage specifically for a directory within Cypress running your tests

Currently, I am utilizing Cypress and Nyc configurations within my project. The folder structure is organized as follows: |/project | /coverage/ /lcov-report /index.html |/cypress | /main /car /car.spec.tsx /color.spec.tsx ... | ...

Verifying Whether Objects in TypeScript File Adhere to a Certain Interface

Currently, I am in the process of developing a procedure that scans through a collection of *.ts files within a directory to identify those containing a class that implements a specific interface. While my preference is to be able to detect multiple classe ...

Error: No accessible element with the role "link" could be located within the Next.js application

I encountered an issue in my Next.js application where I received the following error message: TestingLibraryElementError: Unable to find an accessible element with the role "link" This error occurred while trying to perform the assertion below: expect(sc ...

What is the best way to include the parameter set in the interceptor when making a post request?

-> Initially, I attempt to handle this scenario in the axios request interceptor; if the parameter is uber, then utilize a token. If the parameter is not uber, then do not use a token. -> Afterward, how can I specify uber as a parameter in the custo ...

Troubleshooting issue with centering items in NextJS using tailwindcss

I recently set up my NextJS project with tailwindcss by following the official documentation provided here. (Make sure to check out the section for tailwind) While some tailwindCSS commands like "bg" for background color and "width" are working as expecte ...

Dynamic data manipulation with Angular ReactiveForms

One of the challenges I am facing involves using formArray for my list of products. Specifically, I am trying to access the value of product_code in my .ts file similar to [ngModel] so that I can manipulate the data accordingly. Can anyone provide guidance ...

Prevent the "Invalid element type" error when using React.createElement in Higher Order Components in React

My goal is to create the PrivateRoute Higher Order Component (HOC) that will verify if the user is authenticated before rendering a specific component, and if not, redirect them to the login page. Below is the code for the PrivateRoute HOC: import React f ...

The variable 'key' is declared in the Google Chrome extension V3 local storage, but it appears that its assigned value is never actually accessed

In my TypeScript code, I have defined a function like so: setLocalStorage: async (key: string, value: string): Promise<string> => { return new Promise((resolve, reject) => { chrome.storage.local.set({ key: value }, funct ...

Ways to generate multiple instances using create-next-app

I'm currently using this tool to help me develop a Next app: Encountering the following issue: create-next-app --example with-next-i18next with-next-sass with-next-seo next-learn An error occurred. The example named "with-next-i18next" could not be ...

Unable to fake a fetch request using the 'fetch-mock-jest 1.5.1' library

I am attempting to simulate a fetch call using thefetch-mock-jest library, but the code continues to try accessing the remote address and ultimately fails with the error message FetchError: request to https://some.domain.io/app-config.yaml failed, reason: ...

Adding jQuery and other libraries to Typescript for optimal functionality

After spending days researching and struggling, I am reaching out here for clarification on the process of importing a library in Typescript. I used to just add the script tag and everything would work fine. Now that I am working on building a MEAN-Stack ...

What is the best way to use Shadcn to incorporate a calendar that takes up half of my website?

Currently, I am in the process of developing a scheduling appointment system. My main challenge is getting the calendar to take up half of my page's space. Despite my attempts to adjust its height and width, I have not been successful in seeing any ch ...

Encountering difficulty in reaching the /login endpoint with TypeScript in Express framework

I'm currently working on a demo project using TypeScript and Express, but I've hit a roadblock that I can't seem to figure out. For this project, I've been following a tutorial series from this blog. However, after completing two parts ...

Using Typescript to Import One Namespace into Another Namespace

Is it possible to export a namespace from one typescript .d.ts file and then import that namespace into another .d.ts file where it is utilized inside of a namespace? For instance: namespace_export.d.ts export namespace Foo { interface foo { ...

Setting up TypeScript in Jest without the need for webpack

Currently, I'm developing an NPM module using TypeScript without the use of Webpack for compiling scripts. I need some guidance on configuring Jest to properly run tests with TypeScript files. Any recommendations? // test.spec.ts import {calc} from ...

Defining the TypeScript interface for the onClick event in ReactJS

If you're looking to dive into React development, the tutorial on reactjs.org is a great place to start. While the tutorial code is in JavaScript, I've been working on converting it to TypeScript. I've successfully translated most of the c ...

The issue of process.server being undefined in Nuxt.js modules is causing compatibility problems

I've been troubleshooting an issue with a Nuxt.js module that should add a plugin only if process.server is true, but for some reason it's not working as expected. I attempted to debug the problem by logging process.server using a typescript modu ...

Separating HTML content and text from a JSON response for versatile use within various sections of an Angular 2 application using Typescript

Hello there! I am currently utilizing Angular 2 on the frontend with a WordPress REST API backend. I'm receiving a JSON response from the service, however, the WP rest API sends the content with HTML tags and images embedded. I'm having trouble s ...

Verify if the date surpasses the current date and time of 17:30

Given a date and time parameters, I am interested in determining whether that date/time is greater than the current date at 17:30. I am hoping to achieve this using moment js. Do you think it's possible? This is what I have been attempting: let ref ...

Tips for successfully typing the backtick character when transitioning to Typescript:

I am currently working on a Typescript Vue project involving Leaflet. I came across some code for lazy-loading map markers, but it was written in Javascript. Although the code works fine, I keep receiving errors and warnings from VSCode because this is not ...