'React' refers to a UMD global, but the current file is a module
Asked Answered
P

27

346

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;
Peccadillo answered 3/11, 2020 at 2:37 Comment(3)
"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.Freshwater
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: github.com/facebook/create-react-app/pull/9645.Peccadillo
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.Constipate
R
64

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

Redmon answered 4/11, 2020 at 9:22 Comment(3)
Hi, since TypeScript 4.1 is already out, how do you make it work? Is it the "jsx": "react-jsx" option?Footstone
@Footstone Exactly. If you are using VSCode, make sure you select the right version of TypeScript. LinkRedmon
Nope. It didn't work, is there anything missing in the types option?Outstare
P
549

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

Prude answered 2/1, 2021 at 12:49 Comment(16)
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.Gales
If you have done all this but still get the error, try closing and re-opening vscode.Subjectivism
Doesn't work if you use Next. Next overwrites the jsx option when running npm run dev.Edmead
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.Kippy
Worth also mentioning that you should have something like "include": ["**/*.tsx"] in your tsconfig.json to include the tsx files.Thunderhead
A restart of your IDE may help if you've updated it and it's still complainingWorldly
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?Gales
@Gales did you restart your IDE? It worked for me when i restarted the IDE :)Unsnarl
I have this problem with Storybooks and Tests.Outstare
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 serverDrunkard
@Gales 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-ignored the return statement and things seem ok.Pharyngeal
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 #49708203)Martingale
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".Blunt
It will also work fine with "jsx": :"preserve" in your TSConfig. Just don't forget to restart VSCode as @Subjectivism suggested.Oxytocic
@Edmead 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.Dram
This answer is simply not true. You can absolutely have the latest versions of both React and Typescript, and have "jsx": "react-jsx", and STILL get this error.Stane
C
152

Adding

import React from 'react'

fixes this issue

Cubical answered 26/11, 2021 at 9:30 Comment(5)
The new JSX doesn't require import of React: docsPeccadillo
react import fixes the issue, dont know why. We might need some clarification hereSnooze
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 bobbyhadz.com/blog/… but that did not work. where do I find the tsconfig.json? My project seems to be missing it.Soapbark
reloading vs code after added the right tsconfig worked, we do not need to import reactLands
This also leads to unused imports if you have that turned on in eslintMarilumarilyn
R
64

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

Redmon answered 4/11, 2020 at 9:22 Comment(3)
Hi, since TypeScript 4.1 is already out, how do you make it work? Is it the "jsx": "react-jsx" option?Footstone
@Footstone Exactly. If you are using VSCode, make sure you select the right version of TypeScript. LinkRedmon
Nope. It didn't work, is there anything missing in the types option?Outstare
C
40

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'
Cavallaro answered 1/6, 2022 at 10:28 Comment(1)
this is the right answer, since react 18 support es2020/esnextRaseta
S
35

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

Senegal answered 16/11, 2022 at 22:13 Comment(5)
This works! Turned out that I included .ts files and not .tsx files.Murray
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 youBridgehead
This solves my problem. I am also using Next.js and have tsx files in subfolders.Bureaucratic
This is the real answer. Besides not working, "restart the ts server" and "react-jsx" are not even trying to address the underlying problem.Argillaceous
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!Siskind
G
33

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

Giddings answered 27/12, 2022 at 15:51 Comment(5)
It works - but if you want to avoid reopening VSCode: CMD + SHIFT + P and choose > Reload Window.Dryfoos
This worked; MacOS/VSCode.Wanonah
This worked for me, the warning usually shows up for me when switching between branches.Puissant
for me re running my react app worked. open in a new terminal port.Mccallum
Worked for me on windows 11 alsoTarsier
J
20

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

Jerrine answered 20/12, 2022 at 4:23 Comment(0)
T
20

I fixed it using this:

{
  ...
  "compilerOptions": {
     ...
    "jsx": "react",
    "allowUmdGlobalAccess": true,
  }
}
Tice answered 5/6, 2023 at 20:5 Comment(1)
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 and why when you convert your create react app from js to ts it needs this conf in your tsconfig.json.Fuzee
D
8

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

Dominick answered 24/8, 2022 at 20:59 Comment(0)
T
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".

Tartan answered 13/12, 2022 at 18:22 Comment(0)
K
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 ***
        ...
      },
    },
  },
  ...
};
Kore answered 5/5, 2022 at 19:56 Comment(0)
H
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.

Haerle answered 30/5, 2023 at 14:9 Comment(1)
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 docsHaerle
C
3

*Just set jsx : "react-native" *

{
   "compilerOptions": {
    "jsx": "react-native",
    ...
}
Clearway answered 2/11, 2023 at 23:50 Comment(2)
Hello, please don't post code only and add an explantation as to why you think that this is the optimal solution. People are supposed to learn from your answer, which might not occur if they just copy paste code without knowing why it should be used.Cranford
create-react-app is for SPA JavaScript apps in the browser; it has nothing to do with react-native. That's a completely different library.Ankylosaur
R
3

If you are using VS Code, rather than restarting the entire project, you can usually simply restart the Typescript Server by opening the command palette (⌘+⇧+P on MacOS or ⌃+⇧+P on Windows) and typing "Restart TS Server" + Enter

Restart Typescript Server in the Command Palette

Risibility answered 25/1 at 19:56 Comment(1)
Thanks. So it was just a IDE tweak indeed...Seldon
S
3

For those who are using vite:

specify

"jsx": "react-jsx"

in tsconfig.node.json

refer to Why does Vite create two TypeScript config files

Sicyon answered 6/2 at 22:20 Comment(0)
S
2

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

import * as React from "react"

Skipbomb answered 22/11, 2022 at 10:40 Comment(0)
S
2

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.

Sulph answered 10/1, 2023 at 13:48 Comment(0)
L
1

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

Lindahl answered 5/4, 2023 at 11:29 Comment(0)
H
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

Hybridism answered 2/6, 2023 at 9:39 Comment(0)
J
1

I was having the same thing but somehow I noticed that
tsconfig.json has jsx as a react, after I removed it than it worked.

{
  ...
  "compilerOptions": {
    "jsx": "react", // this line should be removed
     ...
   }
 }

Please know that i'm using TS for my project.

Jamijamie answered 27/9, 2023 at 8:8 Comment(5)
This gave me a new error (with the same component): Cannot use JSX unless the '--jsx' flag is provided.Rust
hey @TzahiLeh can you please give more details about the error? so I could try to help you.Jamijamie
I'm not sure if I know what this error is about. I tried your suggestion and VSCode, as a result, marked it with what I wrote. Would it help if I give my env specs? (like TS version, node version..)Rust
The error is about the compiler options. If you set up your project with TS then you should be removing "jsx": "react" option from compilerOptions. Have you tried it?Jamijamie
If you want TypeScript to compile .tsx extensions, then you need to have the "jsx": "react" property set in the tsconfig.json file. TypeScript cannot compile .tsx files without it. The error @TzahiLeh pasted is exactly what TypeScript will give you when you try it.Ankylosaur
K
0

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

Kana answered 1/10, 2022 at 1:18 Comment(0)
P
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";

Poston answered 23/2, 2023 at 17:4 Comment(1)
When I import it the error goes away but then my test fails because I'm not referencing React.Placate
C
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
Ceria answered 9/8, 2023 at 0:57 Comment(0)
C
0

If you're new to typescript like me and you're using a props remember to import react I had this code but forgot to import react and this error was generated

const DashboardLayout: React.FC<DashboardLayoutProps> = ({ children }) => {
 return <div  className="bg-red-400 h-screen w-full" >
{/* <Navbar /> */}
{children}
</div>;

};

Cyprinid answered 26/9, 2023 at 15:22 Comment(0)
M
0

To anyone updating an Old app in 2024 to React v17+ with TS:

Check target in your tsconfig.json file, it's probably configured as es5, which is incorrect.

As per TypeScript own docs, when supporting the new Reactor v17 JSX, your target should be "es2015". This is the basic boilerplate for it:

{
    "compilerOptions": {
        "module": "esnext",
        "target": "es2015",
        "jsx": "react-jsx",
        "strict": true
    },
    "include": [
        "./**/*"
    ]
}
Monarda answered 30/3 at 21:43 Comment(0)
A
-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

Anarthria answered 25/6, 2023 at 16:25 Comment(0)
O
-4

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

"strict": false,
Overall answered 1/3, 2023 at 4:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.