283

I updated my project to create react app 4.0, and I'm slowing moving over my files to TypeScript. I know with this new version you don't have to repetitively import React from 'react'. However, within all of my TS files where I'm not importing React I receive this error:

'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.ts(2686)`

I know I can fix it by importing React, but I thought this was no longer needed. Also, could someone explain the meaning of this error?

My basic TSX file

const Users = () => {
    return <>Teachers aka Users</>;
};

export default Users;
Liam
  • 27,717
  • 28
  • 128
  • 190
Rafael
  • 3,593
  • 3
  • 17
  • 27
  • "I know with this new version you don't have to repetitively import React from 'react'" - could you elaborate on this? I'm not sure where this information can come from. – Cerberus Nov 03 '20 at 03:36
  • 1
    In previous versions every file that contained jsx needed an import statement for react. You no longer needed this due to the new jsx transform: https://github.com/facebook/create-react-app/pull/9645. – Rafael Nov 03 '20 at 03:55
  • Yes, but you must ensure that the new jsx transform is actually used. For the current babel-loader it is available as an opt-in, but not set as the default. – Martin Nov 26 '21 at 09:47

21 Answers21

454

Create React App supports the new JSX transformation out of the box in version 4 but if you are using a custom setup, the following is needed to remove the TypeScript error when writing jsx without import React from 'react':

  • typescript of at least version 4.1
  • react and react-dom of at least version 17
  • tsconfig.json must have a jsx compilerOption of react-jsx or react-jsxdev

example:

// tsconfig.json
{
  "compilerOptions": {
    ...
    "jsx": "react-jsx"
    ...
  },
}

TypeScript documentation for its support of React 17 JSX Factories can be found here

Dan Barclay
  • 5,827
  • 2
  • 19
  • 22
  • 2
    I have this configuration and when creating a component I don't need the React import but I have to add it for the tests to pass. I am using RTL with jest. – Watchmaker Jul 14 '21 at 14:36
  • 44
    If you have done all this but still get the error, try closing and re-opening vscode. – ppak10 Jul 17 '21 at 18:12
  • 7
    Doesn't work if you use Next. Next overwrites the `jsx` option when running `npm run dev`. – Paul Sep 10 '21 at 23:20
  • VS 2019 doesn't seem to like this very much either ("Cannot find module `react/jsx-runtime`"). Maybe it's because I didn't start with `npx create-react-app`? For now, sticking with the old `import React from 'react'` way. – General Grievance Feb 15 '22 at 15:02
  • 11
    Worth also mentioning that you should have something like `"include": ["**/*.tsx"]` in your `tsconfig.json` to include the `tsx` files. – sorohan Jul 29 '22 at 05:45
  • 3
    A restart of your IDE may help if you've updated it and it's still complaining – Akshay Rajpaul Aug 12 '22 at 14:44
  • 1
    It's funny I do have all this checks, what makes no mandatory the react import to run the app but I have to add it because of the jest tests... Any solution for that? – Watchmaker Aug 31 '22 at 08:21
  • 1
    @Watchmaker did you restart your IDE? It worked for me when i restarted the IDE :) – ii iml0sto1 Sep 22 '22 at 06:47
  • I have this problem with Storybooks and Tests. – SalahAdDin Oct 02 '22 at 15:34
  • If after this you still get an error, try to restart the TS server - no need to exit VSCode every time. Open the `Command palette` > `Typescript: Restart TS server` – moryama Dec 15 '22 at 16:33
  • @Watchmaker if your tests folder not included in the `tsconfig.json` file, it'll complain even though when you run the test it'll work fine. I just `@ts-ignore`d the return statement and things seem ok. – SIMMORSAL Feb 10 '23 at 16:31
  • Are you using VSCode at a subdirectory of your project? (I'd done this as a workaround to have multiple windows open; turns out the right way is to ask VSCode to "Duplicate" the window via the Command Palette https://stackoverflow.com/questions/49707703/open-the-same-directory-twice) – Nolan Amy Mar 03 '23 at 17:28
  • Instead of restarting vs code itself, you can just restart the TypeScript server by opening the command palette (Ctrl+Shift+P by default) then typing "restart" to filter the list and choosing "TypeScript: Restart TS server". – Ken Lyon Mar 21 '23 at 17:55
  • It will also work fine with `"jsx": :"preserve"` in your TSConfig. Just don't forget to restart VSCode as @ppak10 suggested. – Micros Apr 11 '23 at 12:20
  • @Paul did you ever find how to get around these errors in an NX project? I'm finding if I open any .spec.tsx it blows up and I have to succumb to adding the import of React, which is nuts in 2023. – Neil Gaetano Lindberg Aug 07 '23 at 15:11
117

Adding

import React from 'react'

fixes this issue

KARPOLAN
  • 2,507
  • 1
  • 19
  • 10
  • 47
    The new JSX doesn't require import of React: [docs](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#:~:text=Note%20how%20our%20original%20code%20did%20not%20need%20to%20import%20React%20to%20use%20JSX%20anymore!%20(But%20we%20would%20still%20need%20to%20import%20React%20in%20order%20to%20use%20Hooks%20or%20other%20exports%20that%20React%20provides.)) – Rafael Nov 29 '21 at 15:10
  • 8
    react import fixes the issue, dont know why. We might need some clarification here – ertemishakk Mar 03 '22 at 05:16
  • 2
    Very odd indeed. This issue did not pop up in this project for a few weeks, and after adding that import to the class in question the issue went away. I also updated the project following this steps before https://bobbyhadz.com/blog/react-refers-to-umd-global-but-current-file-is-module but that did not work. where do I find the tsconfig.json? My project seems to be missing it. – humbleSquid Aug 25 '22 at 13:31
  • 2
    reloading vs code after added the right tsconfig worked, we do not need to import react – Sanskar Tiwari Nov 28 '22 at 10:06
  • This also leads to unused imports if you have that turned on in eslint – Eddie Monge Jr Mar 24 '23 at 14:26
60

This error message comes from TypeScript compiler. The React 17 new jsx transform is not currently supported in Typescript 4.0, and will be supported in 4.1.

TypeScript v4.1 Beta - React 17 JSX Factories

Matt Peng
  • 848
  • 6
  • 12
  • 24
    Hi, since TypeScript 4.1 is already out, how do you make it work? Is it the `"jsx": "react-jsx"` option? – SenTisso Dec 06 '20 at 13:55
  • 7
    @SenTisso Exactly. If you are using VSCode, make sure you select the right version of TypeScript. [Link](https://code.visualstudio.com/docs/typescript/typescript-compiling#_using-newer-typescript-versions) – Matt Peng Dec 07 '20 at 14:18
  • Nope. It didn't work, is there anything missing in the `types` option? – SalahAdDin Oct 05 '22 at 10:22
28

What Dan wrote is correct you can change TS config.json:

// tsconfig.json
{
  "compilerOptions": {
    ...
    "jsx": "react-jsx"
    ...
  },
}

Or just import React inside the file Component that's giving you the error:

import React from 'react'
Zach Jensz
  • 3,650
  • 5
  • 15
  • 30
23

My issue here was TypeScript-related and similar, but not exactly the same, as those solutions already published herein.

What was wrong

I added nested directories with source code which were not included in my tsconfig.json.

The solution

Here's how I fixed it, simply adding additional .ts and .tsx paths to include, e.g.

// tsconfig.json
{
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "**/**/*.ts",
    "**/**/*.tsx"
    "<path-to-your-source>.ts",
    "<path-to-your-source>.tsx",
  ],
}

My particular project is a Next.js project. Here's my full tsconfig.json:

{
  "compilerOptions": {
    "sourceMap": true,
    "outDir": "dist",
    "strict": true,
    "lib": [
      "esnext"
    ],
    "esModuleInterop": true,
    "target": "es5",
    "allowJs": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "**/**/*.ts",
    "**/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

The vast majority of the above tsconfig.json was generated via Next.js

Jason R Stevens CFA
  • 2,232
  • 1
  • 22
  • 28
  • 2
    This works! Turned out that I included `.ts` files and not `.tsx` files. – Fayez Nazzal Dec 11 '22 at 12:30
  • Thank you so much. This makes sense as tsconfig.json is used by vscode and other tools ON INCLUDED FILES. For other files, a default configuration is used. Hence the error on them. I love you – Cyril CHAPON Dec 16 '22 at 00:34
  • This solves my problem. I am also using Next.js and have tsx files in subfolders. – newguy Jan 13 '23 at 08:46
  • This is the real answer. Besides not working, "restart the ts server" and "react-jsx" are not even trying to address the underlying problem. – Arajay Apr 27 '23 at 02:24
  • This actually resolved this issue for me, I configured a React+Vite project as an app inside a Turborepo, and the app outside the repo works but when I add it throws the error. Thanks a lot for the catch! – aiherrera May 12 '23 at 22:03
20

For VSCode users, on macOS, simply closing and reopening the project fixed the issue for me.

Liran H
  • 9,143
  • 7
  • 39
  • 52
18

Check your file tsconfig.json

"compilerOptions": {
    ...
    "baseUrl": "src",
    ...
    "jsx": "react-jsx",
    ...
 },

To reload the typescript server in VS Code:

Press Ctrl+Shift+P (Cmd+Shift+P on macOS) to open the Command Palette and type restart, then select the command "TypeScript: Restart TS server".

Montotox
  • 181
  • 1
  • 4
8

I fixed it using this:

{
  ...
  "compilerOptions": {
     ...
    "jsx": "react",
    "allowUmdGlobalAccess": true,
  }
}
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
  • Arigato/Thanks/Dankeschön, but personally I would appreciate it if you could do a bit of explaining why we need this `allowUmdGlobalAccess` and [what is UMD](https://dev.to/iggredible/what-the-heck-are-cjs-amd-umd-and-esm-ikm) and why when you convert your create react app from js to ts it needs this conf in your `tsconfig.json`. – Kasir Barati Aug 24 '23 at 07:44
7

In my case, it was unrelated to any of this.

I was using Visual Studio Code, and I opened the folder not at the root which had tsconfig.json file, but at one level inside at src folder.

I was getting the error: Parsing error: Cannot read file :C\MyProject\tsconfig.json.eslint

Which indirectly caused 'React' refers to a UMD global, but the current file is a module

Reopening folder at project level resolved the issue. :\

Mahesh
  • 3,727
  • 1
  • 39
  • 49
4

In VS Code I had to restart the typescript server. I switched between git branches a lot and this error occurred unexpectedly in a file that had no changes. There were no other changes that could trigger this error. After reloading the error disappeared.

To reload the typescript server in VS Code:

Press Ctrl+Shift+P (Cmd+Shift+P on macOS) to open the Command Palette and type restart, then select the command "TypeScript: Restart TS server".

DiMithras
  • 605
  • 6
  • 14
Maciek
  • 41
  • 4
3

I ran into this issue and finally realized that changing tsconfig.json doesn't work if you have ts-jest set up. Make sure if you have ts-jest set to:

module.exports = {
  ...
  globals: {
    ...
    "ts-jest": {
      ...
      tsconfig: {
        ...
        jsx: "react-jsx", // *** HERE ***
        ...
      },
    },
  },
  ...
};
Tag Howard
  • 194
  • 1
  • 11
3

While this is an incredibly old post at this point, I've noticed multiple comments suggesting to use import React from 'react', including from recent posters - Which are incredibly unhelpful and miss the point of the question. Here are the instructions to get JSX transformation to work in a TS, Webpack, Babel environment and get rid of those pesky UMD global error messages.

  1. Add @babel/core, @babel/preset-react and babel-loader to the project
  2. Add a babel.config.ts with the following code
{
    "presets": [
      ["@babel/preset-react", {
        "runtime": "automatic" // This bit does the transformation
      }]
    ]
  }
  1. Add babel loader rule to webpack module.rules, under ts-loader to load that babel config
{
   test: /\.(js|jsx)$/,
   exclude: /node_modules/,
   use: {
     loader: "babel-loader",
   },
},
  1. Add the following rule to TSConfig.ts "jsx": "react-jsx",
  2. Add this (or variation of pointing to src folder) to TSConfig includes. Make sure you have excludes node_modules too
"include": [
   "./src/**/*.ts",
   "./src/**/*.tsx",
   "./src/**/*.jsx",
   "./src/**/*.js",
],
  1. VERY IMPORTANT STEP FOR VSC-ers. Do ctrl+p in visual studio, type > TypeScript. Somewhere will be an option called TypeScript: Select TypeScript Version . Pick the TS version in node_modules, not the shitty out of date inbuilt VSC TS which should be condemned.
  2. Restart VSC. You should be able to test JSX transformation is working with the following in a .tsx file.
import { FC } from "react";

const Component: FC = () => {
  return <></>;
};

export default Component;  

If you use another implementation of react i.e preact, you will also need to add the following rule to your TSConfig to get this to work "jsxImportSource": "preact",

Also if using a framework like Next, you don't need to do this as its inbuilt and in use by default.

Vayne Valerius
  • 158
  • 1
  • 9
  • Since posting this, I would actually highly recommend using SWC over babel due to speed. They have a full explanation of the setup in their docs – Vayne Valerius Aug 11 '23 at 11:11
1

Depending on the versions used in the project, this might be the required format:

import * as React from "react"

Yılmaz Durmaz
  • 2,374
  • 12
  • 26
1

I was having this error when I mistakenly gave index.ts the component's name .

└── components/
    └── Dialog/
        ├── Dialog.tsx
        └── Dialog.ts // This needs to be index.ts

Changing the name back to index.ts solved it.

Badal Saibo
  • 2,499
  • 11
  • 23
1

As pointed out in a comment by ppak10 unter Dan Barclay's answer, try first restarting Visual Studio Code

Raphael Pinel
  • 2,352
  • 24
  • 26
1

Ok my issue was with Docker Dev Containers in VSCode.

What I did to fix it:

  1. Open up the command pallete with F1

  2. Then look for: TypeScript: Select TypeScript Version...

  3. And then select the Workspace version: enter image description here

dontic
  • 63
  • 5
0

I had this happen when the file was in the root of the project instead of the src folder using Create React App.

Gus Beringer
  • 172
  • 9
0

'React' refers to a UMD global, but the current file is a module. Consider adding an import instead.ts(2686)

Simple answer is to, import React.

import React from "react";

Ateeq Syed
  • 41
  • 4
  • When I import it the error goes away but then my test fails because I'm not referencing React. – Matt Sep 01 '23 at 15:52
0

I had "'React' refers to a UMD global, but the current file is a module. Consider adding an import instead" all over my code base. I tried everything and so many random blog post on this subject. Adding an empty jsconfig.json was a temporary fix. After more hours than I'd like to admit of sifting through/playing with settings/configs, I had at some point turned this setting on without thinking. Search settings and shut if off or add this to your settings.json.

"js/ts.implicitProjectConfig.checkJs": false
lowkey
  • 41
  • 6
-1

How I simply solved this issue: by changing the tsconfig target to a more recent one. One that would be supported by most browsers and servers today, like ES2021.

--> Changed the target from ES5 to ES2021 - and that fixed it!

{
  "compilerOptions": {
    "target": "es2021",
  },
}

Which would make sense since we are using a newer syntax today

For information: here is how my tsconfig file looked like before fix :

    {
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

Notice that I already had the "jsx": "react-jsx" option included in my file - which was (correctly) suggested by Dan, but still not sufficient to fix it

Anaïs
  • 1
  • 2
-3

I'm using Next.js. In tsconfig.json,I changed "strict": true to false then errors disappeared.

"strict": false,
ryukyu
  • 55
  • 1
  • 4