React props are not inherited in Custom Next.js App component

Viewed 330

I created custom next.js App component as a class(with intention to override componentDidMount function with initializing Google analytics).

class MyApp extends App {
    async componentDidMount(): Promise<void> {
        await initializeAnalytics();
    }

    render() {
        const {Component, pageProps} = this.props;

        return (
            <Container>
                <Component {...pageProps} />
            </Container>
        );
    }
};

tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "lib": ["es5", "es2015.promise", "dom"],
        "noImplicitAny": true,
        "noImplicitReturns": true,
        "strictNullChecks": true,
        "suppressImplicitAnyIndexErrors": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "jsx": "react",
        "baseUrl": ".",
        "skipLibCheck": true,
        "paths": {
            "@myapp/*": ["./node_modules"]
       }
   }
}

The problem I'm facing is error TS2339: Property 'props' does not exist on type MyApp.

props field should be inherited from App component that is defined as:

export default class App<P = {}, CP = {}, S = {}> extends React.Component<P & AppProps<CP>, 
S> {
    static origGetInitialProps: typeof appGetInitialProps;
    static getInitialProps: typeof appGetInitialProps;
    componentDidCatch(error: Error, _errorInfo: ErrorInfo): void;
    render(): JSX.Element;
}

Why does compiler complain about missing props field on MyApp component? Shouldn't it be inherited from App component that extends React.Component?

Used versions:

  • Typescript 4
  • Next.js 10.0.0
  • React 17.0.0
  • @types/react 17.0.0
2 Answers

You'll need to add "esModuleInterop": true under compilerOptions in your tsconfig.json file.

I'd also suggest you use "jsx": "preserve" to avoid other React-related issues.

for you to use this.props, the props should be a method in the myApp class. therefore this.props doesnt exist as signaled by the compiler

Related