29

I had generated tsconfig.json with tsc --init,

and then I wrote react code in a .tsx file and got the error Cannot use JSX unless the '--jsx' flag is provided

I stumbled upon this jsx setting of tsconfig

it has jsx in commented mode as

// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react', 'react-jsx'. */

so what do those three options mean? namely preserve, react-native and react

Akshay Vijay Jain
  • 13,461
  • 8
  • 60
  • 73

1 Answers1

35

jsx property allows us to use .tsx files in the project

So following are two steps of using React with Typescript

1.Name your files with a .tsx extension

2.Enable the jsx option

TypeScript ships with three JSX modes: preserve, react, and react-native.

These modes only affect the emit stage - type checking is unaffected.

The preserve mode will keep the JSX as part of the output to be further consumed by another transform step (e.g. Babel). Additionally, the output will have a .jsx file extension.

The react mode will emit React.createElement, does not need to go through a JSX transformation before use, and the output will have a .js file extension.

The react-native mode is the equivalent of preserve in that it keeps all JSX, but the output will instead have a .js file extension.

react-jsx (relevant for React 17) mode helps you to avoid the necessity of importing React in every file where jsx is used, i.e. it will emit

React has introduced a new JSX transform with the release of React 17 which automatically transforms JSX without using React.createElement. This allows us to not import React, however, you'll need to import React to use Hooks and other exports that React provides https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html

https://www.typescriptlang.org/docs/handbook/jsx.html#basic-usage

Akshay Vijay Jain
  • 13,461
  • 8
  • 60
  • 73