TS2786 'Component' cannot be used as a JSX component - reactjs

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:
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.
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.

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.

Error TS2786 often comes from a mismatch in #types/react.
When you have libraries that are dependent on a specific version of #types/react (i.e. v17.0.47) and you have other libraries working with a different major version of #types/react (i.e. v18.0.14), then this can cause compatibility issues when using React.ReactNode or JSX.Element. The type JSX.Element is usually returned by a React Function Component.
You can solve the problem by streamlining your dependencies on #types/react, so that these follow the same major version. You can find all libraries depending on #types/react in your project by executing npm explain #types/react (when a package-lock.json file is present) or yarn why #types/react (when a yarn.lock file is present).
In your specific case there seems to be a dependency from #types/react-calendar to #types/react. Your problem seems to be that there are other dependencies in your project using a different version of #types/react. Maybe you even have a direct dependency on #types/react where the exact version number is different from the #types/react version required by #types/react-calendar.
Here is a video that shows how to inspect the applied version of #types/react in your own project.

This can occur when returning children:
export const Component = ({ children }) => {
//...do stuff
return children
}
To fix, wrap in a fragment:
return <>{children}</>
I believe this is because children may be an array of elements and we are only allowed to return a single element. The usual message for this kind of error is:
JSX expressions must have one parent element.

This issue comes with mismatch in #types/react versions TS2786
Fix it with npm dedupe or yarn dedupe

If there's a yarn user wandering around; who had this issue after doing a react/react-native version upgrade recently; just delete the existing yarn.lock file & the node_modules folder and run yarn install again is what worked for me. :)

After update React native from 0.66.3 to 0.70.6 I faced same issue. I solved the problem by changing the "resolutions" in the package.json
"resolutions": {
// "#types/react": "^17" remove this
"#types/react": "^18.0.8" //adding this
},
// After Change remove node_modules
// run npm i OR yarn

None of the answers above solved my case for the same typescript error TS2786
how I get it work is update tsconfig.json
from
{
"compilerOptions": {
"preserveSymlinks": true,
...
to
{
"compilerOptions": {
"preserveSymlinks": false,
...
or just simply remove it

The problem is because react-route v18 does not support react-virtualized and it should be downgraded.
So the simple way is to downgrade your route as below:
"#types/react": "17.0.0",
"#types/react-dom": "17.0.0"
Then, your app should work properly.

Just add the latest version of react and react-dom in package.json and run below command to re-install react and react-dom
Here , while posting this answer, latest version of react and react-dom is 18.
Steps-
Remove package-lock.json file of your proect
Open package.json of your project.
replace react and react-dom version
"#types/react": "^18",
"#types/react-dom": "^18"
4.Run command
npm install --save-dev #types/react #types/react-dom
Done. It resolved my issue.

I was facing the same issue about this error. I add the below code to my package.json file and got resolved.
"resolutions": {
"#types/react": "17.0.2",
"#types/react-dom": "17.0.2",
"graphql": "^16.5.0"
},

I resolved this issue by changing ``jsx: 'react' in tsconfig.json into jsx:react-jsx

my one got solved after I fixed the RETURN statement of my child component
I had in there:
return; <form></form>
changed to:
return (<form></form>)

Related

Component cannot be used as a JSX component in next.js [duplicate]

Ive been getting these strange type errors on my typescript project for certain packages.
Ex:
'TimeAgo' cannot be used as a JSX component.
Its instance type 'ReactTimeago<keyof IntrinsicElements | ComponentType<{}>>' 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/user/app/node_modules/#types/react-bootstrap-table-next/node_modules/#types/react/index").ReactNode'.
Type '{}' is not assignable to type 'ReactNode'.
I don't get these type errors on my local windows machine but they keep occurring in my linux virtual machine. I've deleted the project many times, cloned my repo and installed packages again in different versions of node and I still get the same type errors.
Checked node 12.18.3, 16.13.1
Here is some quick package json info:
"react-timeago": "^6.2.1",
"react-custom-scrollbars": "^4.2.1",
"react-custom-scrollbars-2": "^4.4.0",
"react": "^17.0.2",
"next": "^12.1.1",
"#types/react-custom-scrollbars": "^4.0.10",
"#types/react-timeago": "^4.1.3",
"#types/react": "^17.0.44",
"typescript": "^4.3.5"
"#types/node": "^14.18.12",
This happens on basic custom components:
MyTst.tsx
import TimeAgo from "react-timeago";
const Mytst = () => {
return (
<div>
<TimeAgo date={"02/02/2022"} />
</div>
);
};
export default Mytst;
I get this error for react-custom-scrollbars-2 as well. There seems to be an issue with matching the types correctly between the library which contains the component and the #types files associated with them. Anyone have any ideas on how to resolve these type errors?
Had the same issue.
Just add this
"resolutions": {
"#types/react": "17.0.2",
"#types/react-dom": "17.0.2"
},
to package.json file and run yarn command.
UPD: Just a bit detailed answer:
#types/react-dom has its own dependencies and one of them is #types/react with a version set to '*' - a major release, that now, probably, refers to 18.
Even if you specify some strict versions in your package.json (without ^) parent package might install its own duplicates of packages that you are already using for its own purposes.
By using resolutions we are specifying strict restrictions for dependencies of dependencies.
You will need to fix the version for #types/react package because many react libraries have dependency set as #types/react : "*", which will take the latest version of the package. (I suppose they just released version 18)
To do that you can add this in your package.json
"resolutions": {
"#types/react": "^17.0.38"
}
It will just work fine with yarn, but if you are using npm, then you will also need to add this in "scripts" section of your package.json
"preinstall": "npm install --package-lock-only --ignore-scripts && npx npm-force-resolutions"
This will simply use npm-force-resolutions package to fix versions from resolutions.
And then after doing npm install, your app should work just fine.
I known issued today
rm -rf node_modules
rm -rf yarn.lock
npm install
just used npm install sovled problem
but I don't know what happend
Had this with Styled Components. Resolutions didn't work for me so here's another
solution:
Brute force type casting:
const ThemeProviderFixed = ThemeProvider as unknown as React.FC<PropsWithChildren<{ theme: string }>>;
Sahil's answer is correct for npm and yarn, but if you are using pnpm, you need a slightly different setup in your package.json file:
"pnpm": {
"overrides": {
"#types/react": "^17.0.38"
}
}
If you are using a monorepo with several packages, this only works at the root package.json file of your repo. You can read more about it here in the pnpm docs.
I also had the same issue, so I updated npm version ^6.0.0 -> 8.0.0 and it was resolved.
Check npm version.
I came across this issue recently when upgrading to React 18 and forgetting to upgrade my corresponding types in devDependencies.
What worked for me was upgrading React types to match in the package.json file as shown
{
...
"dependencies": {
...
"react": "^18.1.0",
},
"devDependencies": {
...
"#types/react": "^18.0.8",
}
}
I recently ran into this with a Yarn monorepo where a Typescript create-react-app subproject had installConfig.hoistingLimits=workspace. This configuration prevents hoisting of dependencies to the top-level of the monorepo.
When running react-scripts start, the type checker was still looking at the top-level #types and not finding the matching #types/react for the version of React configured on the project. The fix that resolved it was to add the following to the tsconfig.json in the subproject:
"compilerOptions": {
...
"typeRoots": ["./node_modules/#types"]
},
...
This points Typescript at the type definitions that are installed for the specific sub-project.
Ok. I ended up fixing this problem but to warn you in advance, there wasn't a magical way to do this.
I basically uninstalled all the #types I think were the offenders. You can find this out by reading your error window. The key was this message in my original error above.
Type 'React.ReactNode' is not assignable to type 'import("/home/user/app/node_modules/#types/react-bootstrap-table-next/node_modules/#types/react/index").ReactNode'.
If you see where the node module types are pointing to and its not associated with your library, then remove it. In my case, my issue was the package TimeAgo and the type error was showing that types were assigned to a different package. So I uninstalled it and kept cycling through the errors until it went away.
Then I use npm run build to do type checks and instruct me which types I had to reinstall. (There is probably a better way to do this part but it worked for me even though it was tedious.)
This issue seems to happen when you have a ton of different libraries and their types that have similar dependencies and overtime if they aren't needed, don't do what I do and just keep them piled up in your package.json.
So if you think any type can have conflicts with your library, uninstall and see if the error goes away, and then reinstall if other type errors appear that say the dev type package is missing. I also had some #type packages as dependencies instead of devDependencies which I removed and moved back into dev. Don't know if that played a part.
When in doubt, remove all applicable types and see if the issue is resolved.
If you have older version of npm, just update npm to version > 8.0.0.
It worked for me.
I had npm version 6.x.x. I tried many solutions, but update npm to new version fix this problem easy.
for npm!
check which version of node and npm you have installed.
if you update to 8.x, npm provides you the same thing as resolution does for yarn but its"overrides".
update your package like this:
"overrides": {
"#types/react": "17.x.x",
"#types/react-dom": "17.x.x"
}
my npm and node versions were up to date on local instance, but not on git ci. After the update, it was working without to override the versions for react and react-dom.
Unfortunately in my case I can't use the most voted answer since I need #types18 since I need to use the latest hooks from react#18 like useId and I can't import them using #types/react#17 since they have no exported members for those hooks.
I was able to use latest types fixing the broken typed deps, thanks to #Chris Web' s answer. For example for the Redux Provider:
// temp fix due to #types/react#18
const Provider = _Provider as unknown as React.FC<{
children?: JSX.Element | string;
store: any;
}>;
The store: any is not ideal, but it's just a temp fix.
You can solve this issue by following the above solution for react
"resolutions": {
"#types/react": "17.0.2",
"#types/react-dom": "17.0.2"
},
and for react-native you don't need to add type for react-dom
"resolutions": {
"#types/react": "17.0.2",
},
After this if you still getting error for react types,
add the type package separetly for react
npm install -D #types/react#17.0.2
Note - don't add "^" in resolution as it will try to install the latest version of packages which may cause the same problem.
Problem
For those who have this type of error in the APP and are using yarn instead of npm.
Solution
Just add the to resolutions and preinstall script inside the package.json file and them execute yarn preinstall and yarn.
package.json
"resolutions": {
.....
"#types/react": "^17.0.38"
....
},
"scripts": {
......
"preinstall": "yarn --package-lock-only --ignore-scripts"
......
},
References
Source
Slightly different answer that worked for me (in case the above doesn't work for you). I had a node_modules folder in my user root. So my project folder looked like this:
~/checkouts/project/node_modules
but I also had a node_modules folder installed at the user root (probably an accident at some point):
~/node_modules
The way npm packages work is it crawls up the directory structure grabbing npm packages along the way. After removing this directory the problem went away.
Tested this on two windows machines one mac and one ubuntu. One win machines was fine (no error on build), the other wind machine gave this error on build. Mac was also fine but ubuntu was also giving this error on build. I was frustrated. Tested with different node versions but that did not help.
In the end had to update some types versions (not sure though if all four needed to be updated but after the update error disappeared):
"#types/react": "^16.14.3",
"#types/react-dom": "^16.9.10",
"#types/react-router": "^5.1.11",
"#types/react-router-dom": "^5.1.7",
to:
"#types/react": "^18.0.15",
"#types/react-dom": "^18.0.6",
"#types/react-router": "^5.1.18",
"#types/react-router-dom": "^5.3.3",
i tried it in two ways, with yarn's resolution it solved it, but then i deleted my yarn.lock and updated the react's type and it worked for me too without using yarn's resolution
yarn upgrade #types/react#^18.0.21
I posted a different answer but it was basically a duplicate answer so I'll provide another approach.
If you're using yarn, you can run yarn dedupe and it will make the necessary changes to your yarn.lock file. It will consolidate any references to the same package to resolve to the correct version. As you can see from here, the - lines are what were removed and the + line is modified and saved:
-"#types/react#npm:*, #types/react#npm:>=15, #types/react#npm:>=16.9.0":
- version: 17.0.43
- resolution: "#types/react#npm:17.0.43"
- dependencies:
- "#types/prop-types": "*"
- "#types/scheduler": "*"
- csstype: ^3.0.2
- checksum: 981b0993f5b3ea9d3488b8cc883201e8ae47ba7732929f788f450a79fd72829e658080d5084e67caa008e58d989b0abc1d5f36ff0a1cda09315ea3a3c0c9dc11
- languageName: node
- linkType: hard
-
-"#types/react#npm:^18.0.0":
+"#types/react#npm:*, #types/react#npm:>=15, #types/react#npm:>=16.9.0, #types/react#npm:^18.0.0":
"#types/react#npm:*, #types/react#npm:>=15, #types/react#npm:>=16.9.0"
was consolidated into
"#types/react#npm:*, #types/react#npm:>=15, #types/react#npm:>=16.9.0, #types/react#npm:^18.0.0"
In my case, I put the wrong type of value inside a div.
Error
Reason
Fix

ReactJs - Compiled with warning

Warning
(6:29521) autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust shorthand is currently deprecated.
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
WARNING in ./node_modules/bootstrap/dist/css/bootstrap.min.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!./node_modules/bootstrap/dist/css/bootstrap.min.css)
Module Warning (from ./node_modules/postcss-loader/dist/cjs.js):
I encounter this warning while running react-bootstrap(v2.3.1 (Bootstrap 5.1)) with reactjs(v18.1.0). How to solve the problem?
You can add it into package.json
First Step
"resolutions": {
"autoprefixer": "10.4.5"
},
Second Step
yarn install
** If you are using npm
First Step
"overrides": {
"autoprefixer": "10.4.5"
},
Second Step
npm install
** Summarize from https://github.com/twbs/bootstrap/issues/36259#issuecomment-1114855186
Bump bootstrap to 5.2.0 or newer.
Bootstrap 5.1.3 still has this problem.
As I'm typing this, the latest bootstrap 5.2.0 version is 5.2.0-beta1, which given its beta status may or may not be something you want to upgrade to, but upgrading to that will at least solve this problem.
The root cause here is that bootstrap generates CSS with deprecated tags. Notice how your error message implicates bootstrap:
WARNING in ./node_modules/bootstrap/dist/css/bootstrap.min.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!./node_modules/bootstrap/dist/css/bootstrap.min.css)
This problem still exists for me even upgrading to bootstrap 5.2.0-beta1 and upon inspection of the installed bootstrap it appears to be using latest autoprefixer. I see no solution currently. If there is a way to create a js/tsx file to override that would be nice.
Simply setting overrides didn't work for me. I had do go through the following steps :
Add this to package.json:
"overrides": { "autoprefixer": "10.4.5" }
Delete package-lock.json
Delete the node_modules/ directory
Run npm install to install the npm modules back
Go to bootstrap.css or bootstrap.min.css, in my case is bootstrap.min.css
ctrl+F or find text -webkit-print-color-adjust:exact;color-adjust:exact
change the color-adjust to print-color-adjust
problem solved

How to deal with react, react-dom, #types/react and #types/react-dom package versions?

Recently, I upgrade version of react/react-dom in my project from 16.3.2 to 16.8.6 to be able to use hooks and, with some minor changes in my code, everything went well.
But we are using typescript, and when I try to use React.useState(), typescript compiler complains and is unable to compile : Property 'useState' does not exist on type 'typeof React'.
I think the problem is that #types/react and #types/react-dom packages were not up-to-date. So I tried to upgrade them from 16.3.2 to 16.8.5 (16.8.6 doesn't exist for #types/react-dom).
Then I was able to use usestate() but everything else was broken, typescript compiler was complaining about almost every component...
My question is: what should I do ? What is the best approach to upgrade those packages ? Do versions need to be the same ?
Thanks.
import React from 'react';
export default function App() {
const [state, setState] = React.useState();
}
Did you try on that way?
and you are using the right #types in your package.json
"#types/react": "^16.8.14",
"#types/react-dom": "16.8.3",
"typescript": "3.5.3"
Short answer, #types/react and #types/react-dom versions may not be the same.
You have to choose the correct versions based on the versions of typescript and react that you're using.
Here's how:
For example, imagine you are using react 17.x.y. Because of that, you would look at the 17.x.y versions of #types/react. To choose the final one, you would look at the tag next to each one of those and choose the one that matches your typescript version (tsX.Y). Imagine if you are using typescript 3.8.x. You could choose this package:
The same thing for #types/react-dom.

How to update pre-existing dependency when using create-react-app?

I am using create-react-app for a project. I installed various eslint plugins etc, however, we all know that create-react-app already comes with certain dependencies that are not shown in package.json.
I want the newest eslint version which is currently 5.3.0. Create-react-app comes with 5.16.0. WITHOUT EJECTING, how do I bring this dependency to the newest version without breaking everything?
I get the following error:
The react-scripts package provided by Create React App requires a dependency:
"eslint": "^5.16.0"
Don't try to install it manually: your package manager does it automatically.
However, a different version of eslint was detected higher up in the tree:
:\node_modules\eslint (version: 5.3.0)
Things in package.json will take precedence so if you upgrade version of eslint, react-scripts should always take the latest version.
There is a small loophole though. If you fiddle too much with dependencies you might get the warning about mismatch version by react-scripts. To avoid that you can create .env file and can specify the following.
SKIP_PREFLIGHT_CHECK=true
I just solved this issue, the error says:
The react-scripts package provided by Create React App requires a dependency:
"eslint": "5.16.0"
but also says you have another version at package.json that's
\node_modules\eslint (version: 5.3.0) in my case was 6.1.0
so my solution was:
I searched for the dependency called eslint and updated the version similar to Create React App expected "eslint": "^5.16.0" at package.json
Then run npm install and now you can run npm start... if you have troubles with slint-plugin-import just update the version as well.

Duplicate Types error when using react, reactdom and react-redux types together

So I am trying to use react-redux with typescript. This is what my package.json looks like
"dependencies": {
"#types/react-dom": "15.5.0",
"#types/react": "15.0.4",
"#types/react-redux": "4.4.39",
"axios": "0.16.2",
"react": "15.0.0",
"react-dom": "15.0.0",
"redux": "3.6.0",
"react-redux": "5.0.6",
"redux-thunk": "2.1.0",
"office-ui-fabric-react": "1.0.0"
}
Now when I do yarn install. I see multiple react types get installed. Once for #types/React. One for #types/React-redux and #types/react-dom inside each of its own node_modules folder. And the version of the types these modules install internally are very different as I see in my yarn.lock file.
When I try to compile this, I get the errors like
error TS2304: Cannot find name 'DetailedHTMLFactory'.
Subsequent variable declarations must have the same type
The error disappears if I duplicate all the nested #types and just keep teh top level #types/react.
Whats a better way to do this, so that duplicate types issue doesn't appear ?
Since you are using yarn, the easiest direction might be to use resolutions in the package.json file to force specific versions of the typings, see https://github.com/yarnpkg/yarn/pull/4105
Other than that you would have to figure out which specific versions of these typings work with one another. Basically look at #types/react-dom dependency list and then include the same version of #types/react in your project.
You should try to remove your node_modules folder, run yarn cache clear and reinstall everything. There is an issue on the typescript repo about this behaviour ( I ran into it recently with one of my side projects ) that i'll try to find and link to this answer.
So I finally fixed this by excluding node_modules folder.
Put "node_modules" in the "exclude" section of tsconfig.json .

Resources