''Component' cannot be used as a JSX component. Nextjs

This is how _app.tsx looks:

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

and I am getting this error while building project:

Type error: 'Component' cannot be used as a JSX component.
  Its element type 'ReactElement<any, any> | Component<{}, any, any> | null' is not a valid JSX element.
    Type 'Component<{}, any, any>' is not assignable to type 'Element | ElementClass | null'.
      Type 'Component<{}, any, any>' is not assignable to type 'ElementClass'.
        The types returned by 'render()' are incompatible between these types.
          Type 'React.ReactNode' is not assignable to type 'import("/Users/user/node_modules/@types/react/index").ReactNode'.
            Type '{}' is not assignable to type 'ReactNode'.

These are the react versions:

"react": "17.0.2",
"react-dom": "17.0.2",
"@types/react": "17.0.26",

I tried to switch to 18 version, it worked but, I got this error: Hydration failed because the initial UI does not match what was rendered on the server



Solution 1:[1]

Add the following code into package.json file

"resolutions": {
  "@types/react": "17.0.2",
  "@types/react-dom": "17.0.2"
}

Then Reinstall the packages

yarn
  • if using npm
npm i

Solution 2:[2]

I think that is because you did not set typescript properly in your project. I think, currently, when you install next.js, you should have option to select typescript. If not

npm install --save-dev typescript @types/react @types/node.

in tsconfig.json, you should have "jsx": "preserve" in compiler options. It allows us to use .tsx files in the project. an example of tsconfig.json

  • I think this might be the issue. In order to indicate that we are returning jsx we have to wrap the component with (). but in your component you have

    return <Component {...pageProps} />
    

even though I tried to put (), vscode omits it. So try arrow function:

const App = ({ Component, pageProps }: AppProps) => (
  <Component {...pageProps} />
);

export default App;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ashirbad Panigrahi
Solution 2