Utilizing the NPM package as a JSX Component is prohibited due to type errors

I've been encountering some unusual type errors in my TypeScript project with certain packages. For example:

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

Interestingly, I don't encounter these type errors on my local Windows machine, but they persist on my Linux virtual machine. I have tried deleting and re-creating the project multiple times, cloning the repository, and reinstalling packages using different versions of Node, yet the same type errors keep popping up.

I have checked Node versions 12.18.3 and 16.13.1

Below is some information from my package.json file:

"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",

These type errors seem to occur with basic custom components like:

MyTst.tsx
import TimeAgo from "react-timeago";

const Mytst = () => {
  return (
    <div>
      <TimeAgo date={"02/02/2022"} />
    </div>
  );
};

export default Mytst;

The error also arises for react-custom-scrollbars-2. It appears that there might be an issue in correctly matching the types between the library containing the component and its associated @types files. Does anyone have any suggestions on how to resolve these type errors?

Answer №1

Encountered a similar issue and found a solution:

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

Add the above code block to your package.json file and then execute the command yarn.

Update: Providing more context for clarity:

The package @types/react-dom has its own dependencies, including @types/react with an unspecified version (denoted as '*') which may now default to version 18.

Even if you define specific versions in your package.json, the parent package may introduce duplicate dependencies unintentionally.

Using the resolutions field helps enforce strict rules for these nested dependencies.

Answer №2

To ensure compatibility with various React libraries, it is important to update the version of the @types/react package. Many libraries have set their dependency to @types/react : "*", which automatically fetches the latest version (currently assumed to be 18).

You can specify the desired version in your package.json file by adding the following:

"resolutions": {
  "@types/react": "^17.0.38"
}

If you are using npm instead of yarn, make sure to include the following in the "scripts" section of your package.json:

"preinstall": "npm install --package-lock-only --ignore-scripts && npx npm-force-resolutions"

This command utilizes the npm-force-resolutions package to manage version conflicts.

After running npm install, your application should function properly without any issues.

Answer №3

Encountered a similar issue while using Styled Components. When resolutions weren't effective, I found an alternative solution:

Implementing brute force type casting:

const CustomThemeProvider = ThemeProvider as unknown as React.FC<PropsWithChildren<{ theme: string }>>;

Answer №4

Today, I encountered an issue.

rm -rf node_modules
rm -rf yarn.lock
npm install

I managed to solve the problem by simply using npm install, but I am unsure of what actually happened.

Answer №5

I encountered a similar issue while working on a Yarn monorepo that included a Typescript create-react-app subproject with the configuration

installConfig.hoistingLimits=workspace
. This setup prevented dependencies from being hoisted to the top-level of the monorepo.

During the execution of react-scripts start, the type checker was referencing the top-level @types directory instead of locating the appropriate @types/react for the specified React version in the project. To resolve this issue, I added the following snippet to the tsconfig.json within the subproject:

"compilerOptions": {
  ...
  "typeRoots": ["./node_modules/@types"]
},
...

By including this configuration, Typescript was able to access the relevant type definitions specific to the sub-project.

Answer №6

Sahil's response is accurate for npm and yarn, but if you opt for pnpm, a slightly different configuration is required in your package.json file:

"pnpm": {
  "overrides": {
    "@types/react": "^17.0.38"
  }
}

If you are managing a monorepo with multiple packages, remember that this setting applies only to the primary package.json file at the root of your project. For more detailed information, refer to the documentation on pnpm overrides.

Answer №7

Encountering a similar problem, I decided to upgrade my npm version from ^6.0.0 -> 8.0.0 which successfully resolved the issue at hand.

Make sure to verify your current npm version as well.

Answer №8

During my recent upgrade to React 18, I encountered an issue that arose from forgetting to update the corresponding types in devDependencies.

To resolve this issue, I simply updated the React types in the package.json file to ensure they matched correctly:

{
    ...
    "dependencies": {
        ...
        "react": "^18.1.0",
    },
    "devDependencies": {
        ...
        "@types/react": "^18.0.8",
    }
}

Answer №9

After encountering a challenging issue, I managed to find a solution. However, it's important to note that there was no easy fix for this problem.

To resolve the issue, I took a proactive approach by uninstalling all @types packages that I suspected were causing the errors. Identifying these problematic packages simply involved reviewing the error messages displayed in my window. The key hint came from the specific error message highlighted above.

The error indicated: "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 notice that the node module types are pointing to a different package unrelated to your library, it's best to remove it. In my case, the culprit was the TimeAgo package, which was causing type conflicts with another package. By systematically removing and rechecking the errors, I was able to pinpoint and eliminate the root cause of the issue.

Subsequently, I utilized npm run build to conduct type checks and identify the necessary types that needed reinstatement. While this process was somewhat tedious, it effectively resolved the problem in my case.

This type of issue often arises when multiple libraries share similar dependencies. Over time, unused or redundant types can accumulate in your package.json file if they are not properly managed.

If you suspect that certain types may be conflicting with your library, consider uninstalling them temporarily to see if the error disappears. Reinstall any essential types as needed, especially if additional errors indicate missing dev type packages. It's also worth noting that some @type packages might function better as devDependencies rather than regular dependencies.

When unsure about which types are causing conflicts, a systematic approach of removal and reinstallation is recommended to troubleshoot and ultimately resolve the issue.

Answer №10

If your npm version is outdated, simply upgrade it to a version greater than 8.0.0. This solution worked like a charm for me.

Having an older npm version (6.x.x), I experimented with various fixes, only to find that updating npm to the latest version quickly resolved the issue.

Answer №11

Don't forget to check your npm version!

Make sure to verify the versions of node and npm that are currently installed on your system. If you decide to upgrade to version 8.x, npm will offer a similar feature as resolution in yarn, known as "overrides." To update your package, use the following code:

"overrides": {
  "@types/react": "17.x.x",
  "@types/react-dom": "17.x.x"
}

While my local instance had the latest npm and node versions, this was not the case for the git ci environment. However, after performing the necessary updates, the project ran smoothly without requiring any overrides for react and react-dom versions.

Answer №12

Unfortunately, I am unable to use the top-voted solution in my situation as I require @types18 for utilizing the latest hooks from react@18 such as useId. Using @types/react@17 is not feasible as it does not provide exported members for these hooks.

Thanks to the response from @Chris Web, I managed to make use of the latest types by resolving the issues with typed dependencies. For instance, for the Redux Provider:

// temporary workaround for @types/react@18
const Provider = _Provider as unknown as React.FC<{
  children?: JSX.Element | string;
  store: any;
}>;

Although using store: any is not ideal, it serves as a temporary fix for now.

Answer №13

To fix this issue, simply implement the solution provided above for react.

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

For react-native, there is no need to include types for react-dom:

"resolutions": {
"@types/react": "17.0.2",

}, If you continue to encounter errors with react types, install the type package separately for react:

npm install -D @types/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abcdefabc9c8caece5fbf5ebeb84efe9">[email protected]</a>

Remember - do not use "^" in the resolution as it will attempt to install the latest package versions, potentially causing the same issue.

Answer №14

Issue

If you encounter a specific error in the application while utilizing yarn rather than npm.

Fix

To resolve this, include the necessary changes to the resolutions and preinstall script within the package.json file and then run yarn preinstall followed by yarn.

  • package.json
"resolutions": {
    .....
    "@types/react": "^17.0.38"
    ....
  },


"scripts": {
    ......
    "preinstall": "yarn --package-lock-only --ignore-scripts"
    ......
  },

Additional Information

  • Source

Answer №15

Here's a slightly altered solution that helped me resolve the issue (just in case the previous one doesn't do the trick for you). I discovered that there was a node_modules folder located in my user root directory. This is how my project folder structure appeared:

~/checkouts/project/node_modules

In addition, there was an extra node_modules folder mistakenly installed in the user root directory:

~/node_modules

Keep in mind that npm packages operate by scanning through the directory structure and collecting npm packages as it goes. Once I removed this unnecessary directory, the problem was resolved.

Answer №16

After conducting tests on two Windows machines, one Mac, and one Ubuntu, it was discovered that one of the Windows machines had no build errors, while the other Windows machine and Ubuntu both experienced errors during the build process. Despite testing with different node versions, the issue persisted. Ultimately, updating some types versions resolved the error:

"@types/react": "^18.0.15",
"@types/react-dom": "^18.0.6",
"@types/react-router": "^5.1.18",
"@types/react-router-dom": "^5.3.3",

Answer №17

After experimenting with different methods, I first used yarn's resolution to resolve the issue. However, when I deleted my yarn.lock file and updated the type for React, that also resolved the issue without relying on yarn's resolution.

yarn upgrade @types/react@^18.0.21

Answer №18

I initially shared a different response, but upon realization that it was essentially a duplicate answer, I will present an alternative perspective.

For those utilizing yarn, executing yarn dedupe will induce the necessary adjustments to your yarn.lock file. This action will amalgamate any mentions of the same package to resolve to the accurate version. The removals are denoted by the - lines while modifications and saves are represented by the + line as illustrated below:

-"@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 streamlined into

"@types/react@npm:*, @types/react@npm:>=15, @types/react@npm:>=16.9.0, @types/react@npm:^18.0.0"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to mandate the declaration or type of a function in TypeScript?

Let me present my dilemma: I am aiming to create a declaration file containing TypeScript function models. This file will be utilized by various individuals to build their own programs. To achieve this, I have crafted a def.d.ts file with a small example ...

Using Typescript to deliver the parent component's props to its children prop

I have a goal to create a versatile component that can accept different props based on its usage in the project. The component should output its children prop along with all the given props (flow-through) and potentially some new constants calculated based ...

Encountering a 404 error with Angular 6 routing after refreshing the page when using an Nginx proxy

I currently have my angular application running within a docker container, exposed on port 83. Additionally, I have a separate spring-boot rest app running inside another docker container, exposed on port 8083. On the host server, there is an Nginx server ...

Encountering challenges with unresolved WebPack peer dependencies

Having a strange issue here. I'm attempting to run an npm install on a react/redux boilerplate solution I found on GitHub but running into unmet peer dependency problems. The odd thing is, from my perspective, there shouldn't be any issues at all ...

What is the best way to generate a distinct identifier for every div element on a

Currently, I am working with Angular 2 and have a div element that I need to repeat in my HTML markup. This particular div contains a click event attached to it. Here is the code snippet: HTML: <div class="row"> <button class="btn btn-primar ...

Exploring the power of TypeScript within the useContext hook

I recently started following a React tutorial on YouTube and decided to convert the project from JavaScript to TypeScript. However, I am facing difficulties with implementing useContext in my code. Any help or guidance would be greatly appreciated. If yo ...

Minimizing CSS Using Laravel Mix

Download Node.js Get NPM installed Navigate to the main directory of your project and open the file: webpack.mix.js. mix.styles([ 'public/css/vendor/normalize.css', 'public/css/vendor/videojs.css' ], 'public/css/all.css&ap ...

Avoid stopping Bootstrap Vue's events

Need help with a b-form-select control in Bootstrap Vue. Trying to execute a function when the value changes, but want the option to cancel the event and keep the original value. Complicating matters, the select is in a child component while the function ...

Encountered errors while trying to install ng-bootstrap, installation of package was unsuccessful

I am currently developing an Angular application and I require an accordion component for it. My efforts to install the ng-bootstrap package using the command 'ng add @ng-bootstrap/ng-bootstrap' have been unsuccessful as the installation fails ev ...

Unable to trigger an event from an asynchronous method in TypeScript

In my scenario, I have a child component that needs to emit an event. However, I require the parent handler method to be async. The issue arises when the parent does not receive the emitted object in this particular configuration: Parent Component <co ...

Tips for getting Nativescript listview to function properly

I am currently developing an app using nativescript and angular 2. I am facing some issues while trying to implement the nativescript listview component. Whenever I run the app, all I see is " [object object] ". Below is my view code : <grid-layout c ...

Encountering a 403 error when attempting to upload files to Google Cloud Storage (GCS) using Signed URLs

The main aim is to create a signed URL in the api/fileupload.js file for uploading the file to GCS. Then, retrieve the signed URL from the Nextjs server through the nextjs API at localhost://3000/api/fileupload. Finally, use the generated signed URL to upl ...

There is no index signature containing a parameter of type 'string' within the type '{ appointments: { label: string; id: number; minWidth: number; }[]; }'

Just getting started with React and Typescript. I'm attempting to extract data from the configuration file based on the input(props), but it seems like Typescript is throwing errors. Any suggestions on how to tackle this issue? config.json { "t ...

Restoring previous configuration in Ionic2 from the resume() lifecycle method

Encountering an issue with my ionic2 application where I save the last state in local storage when the app goes to the background. Upon resuming, it checks for the value of lastState in local storage and pushes that state if a value exists. The specific er ...

Mastering Interpolation in React with TypeScript is essential for creating dynamic and interactive UI components. By leveraging the

Incorporating and distributing CSS objects through ChakraUI presents a simple need. Given that everything is inline, it seems the main issue revolves around "& > div". However, one of the TypeScript (TS) errors highlights an unexpected flagging of ...

The parameter type 'router' cannot be replaced with the type 'typeof ...'. The 'param' property is not included in the type 'typeof'

I'm currently working on a node application using TypeScript and have set up routing in a separate file named 'route.ts' import home = require('../controller/homeController'); import express = require('express'); let ro ...

Execute the gulp task following the installation of an NPM package

I have created a compact package hosted on GitHub that serves as a user interface library with just one SCSS file. my-ui-library -- src/styles.scss My goal is for the package to automatically execute a gulp task upon installation that compiles the CSS an ...

How can I subscribe to nested JSON objects in Angular?

I am seeking advice on working with a nested JSON object. Within our server, there is an object located at "/dev/api/sportstypes/2" structured like this; { "NBA": { "link": "https://www.nba.com/", "ticketPrice": 50 }, "UEFA": { ...

Ways to transfer form information to Gmail without the need for nodemailer

While exploring ways to send form data to my Gmail account, I came across the 'nodemailer' package. However, it seems that the package requires my Gmail password and I would also need to reduce the security level of my Gmail account. Is there a m ...

Is condition checking taken into consideration by Typescript?

I keep encountering this strange TypeScript compile warning that just won't go away, even though I believe it shouldn't be there in the first place... Here are the interfaces I'm working with: interface Props { tasks: TaskType[] } inter ...