reactjstypescriptreact-domtsx

TS2786 'Component' cannot be used as a JSX component


I have a React Typescript application that won't compile. Many components have a render method that is typed to return React.ReactNode or React.ReactElement. On compile, many errors similar to the following are reported:

TS2786: 'MessagesWidget' cannot be used as a JSX component.
 Its instance type 'MessagesWidget' is not a valid JSX element.
 The types returned by 'render()' are incompatible between these types.
 Type 'React.ReactNode' is not assignable to type 'import("/home/node/app/node_modules/@types/react-calendar/node_modules/@types/react/index").ReactNode'.

Why is the compiler expecting ReactNode as defined by the types bundled with react-calendar? I do have @types/react-dom installed as a dev dependency.

Other information that might be relevant:

  1. This project was compiling until a couple of days ago and there were no code changes when the compile started failing, so I suspect that a package update triggered this (even if that's not the root cause). The only dependencies that were updated in the time window when the compile started failing were @types/react and @types/react-dom. Rolling these packages back to an older version did not fix the issue, however.
  2. Changing my components render methods to return JSX.Element removes the compiler error, but there are third party components in the application where this is not possible.

Solution

  • I have a solution, it seems that there are a ton of breaking changes in the 18.0.1 type definitions.

    Like you, I could not solve it by rolling back to earlier versions, but investigation lead me to discover that this was because 'react-router' among others was bringing in the '18.0.1' version.

    to get around this, I added the following to my package.json

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

    Then I cleared my node-modules, and my package cache and then re-ran yarn to pull fresh packages.

    The resolutions section is for yarn (which I use). and I think you can use 'overrides' instead of 'resolutions' if you are using NPM.

    npm version should >= 8 https://docs.npmjs.com/cli/v8/configuring-npm/package-json#overrides

    and delete package-lock.json before npm i.