Skip to content
DeveloperMemos

Resolving TypeScript Error in React with JSX without Importing React

React.js, TypeScript, Web Development1 min read

In modern React development, especially with the introduction of React 17, it's common to use JSX without explicitly importing React in every file. However, this can lead to a TypeScript error that confuses many developers. This article will guide you through resolving the TypeScript error "React refers to a UMD global, but the current file is a module."

Understanding the Error

The error occurs when using JSX in TypeScript files without importing React. This happens because TypeScript needs to know how to interpret the JSX syntax. From React 17, React introduced a new JSX transform that does not require importing React into every file, but this needs to be configured correctly in TypeScript.

Prerequisites for the Solution

To solve this issue, ensure you have:

  • React and React-DOM version 17 or higher.
  • TypeScript version 4.1 or higher.

Configuring TypeScript for New JSX Transform

Update your tsconfig.json file to support the new JSX transform. Set the jsx compiler option to react-jsx for development and production builds or react-jsxdev for development builds.

Example tsconfig.json:

1{
2 "compilerOptions": {
3 ...
4 "jsx": "react-jsx",
5 ...
6 }
7}

With this configuration, TypeScript will understand the new JSX transform, and you won't need to import React in files using JSX.

Additional Steps for Next.js Projects

If you're working with Next.js, be aware that Next.js might overwrite the jsx option. In this case, follow the Next.js specific documentation to ensure compatibility.

Wrapping Up

By configuring TypeScript correctly for the new JSX transform, you can enjoy the streamlined developer experience of not having to import React in every file using JSX. This makes your React code cleaner and more enjoyable to write.

Remember to keep your React and TypeScript versions up to date to take advantage of the latest features and improvements.