Home > Software engineering >  Trying to use React.Component in Typescript
Trying to use React.Component in Typescript

Time:11-20

Here's _app.tsx from a bare bones react auth example

import { SessionProvider } from "next-auth/react",
import * as React from "react"
export default function App({
  React.Component,
  pageProps: { session, ...pageProps },
}) {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  )

}

It wont compile because it says Component is an 'any' type I thought the solution was to import Component from React but it doesnt seem to have worked.

CodePudding user response:

you have to define the type of your custom props like below.

import { SessionProvider } from "next-auth/react";
import { AppProps } from "next/app";
import * as React from "react";

interface CustomPageProps {
  session: YOUR_SESSION_TYPE_HERE;
}

export default function App({
  Component,
  pageProps,
}: AppProps<CustomPageProps>) {
  return (
    <SessionProvider session={pageProps.session}>
      <Component {...pageProps} />
    </SessionProvider>
  )
}

CodePudding user response:

You should import Session type from next/auth and use it with CustomProps generic type.

import { Session } from "next-auth";
 // ^^^^^^^^^^^^^^^^

import { SessionProvider } from "next-auth/react";
import { AppProps } from "next/app";
import * as React from "react";

interface CustomPageProps {
  session: Session; // <------------ use it here
}

export default function App({
  Component,
  pageProps,
}: AppProps<CustomPageProps>) {
  return (
    <SessionProvider session={pageProps.session}>
      <Component {...pageProps} />
    </SessionProvider>
  )
}
  • Related