Alex Foxleigh
Alex Foxleigh

Reputation: 1964

Typescript error with NextJS and Context API

I have the following code in my _app.tsx file:

import React from 'react'
import type { AppProps } from 'next/app'

/* Import Styles */
import '@themes/index.scss'

/* Import Template */
import WithAuth from '@templates/with-auth'

// This default export is required in a new `pages/_app.js` file.
export const App = ({ Component, pageProps }: {Component: unknown, pageProps: unknown}): AppProps => {
  return (
    <WithAuth>
      <Component {...pageProps} />
    </WithAuth>
  )
}

export default App

I got the AppProps usage from the nextjs documentation, however I have wrapped the component with a WithAuth component which is basically a template with a MaterialUI ThemeProvider and a react context provider:

 return <div className={styles['grid-page']}>
    <ThemeProvider theme={theme}>
      <GlobalContext.Provider value={globalProps}>
        <HeaderBar />
        <main>
          { children }
        </main>
      </GlobalContext.Provider>
    </ThemeProvider>
  </div>
  }

When I do this, I get the typescript error:

pages/_app.tsx:12:3 - error TS2322: Type 'Element' is not assignable to type 'AppPropsType<Router, {}>'.
  Property 'pageProps' is missing in type 'Element' but required in type 'AppInitialProps'.

 12   return (
      ~~~~~~~~
 13     <WithAuth>
    ~~~~~~~~~~~~~~
...
 15     </WithAuth>
    ~~~~~~~~~~~~~~~
 16   )
    ~~~

  node_modules/next/dist/next-server/lib/utils.d.ts:124:5
    124     pageProps: any;
            ~~~~~~~~~
    'pageProps' is declared here.

pages/_app.tsx:14:8 - error TS2604: JSX element type 'Component' does not have any construct or call signatures.

14       <Component {...pageProps} />

I'm struggling to understand the correct types to add here

Upvotes: 0

Views: 1637

Answers (1)

Nilesh Patel
Nilesh Patel

Reputation: 3317

AppProps should be de-structured.

import { AppProps } from 'next/app'

const MyApp = ({ Component, pageProps }: AppProps) => {
  return (
    <>
      <Header />
      <Component {...pageProps} />
    </>
  )
}

Upvotes: 1

Related Questions