30

While using Typescript with React we have to specify jsx in compilerOptions in tsconfig.json file.

It has preserve, react, react-native, react-jsx etc. as allowed values.

{
  "compilerOptions": {
    "jsx": "react-jsx" | "react" | "react-native" | "preserve"
  }
}

react and react-jsx are mostly used for web I want to understand the difference between the 2 options and which one to choose when

react translates jsx to React.createElement()

react-jsx translates jsx to _jsx() and _jsxs()

Also what is the difference between _jsx() and _jsxs() ?

Rahul Yadav
  • 2,627
  • 5
  • 30
  • 52

1 Answers1

24

Is preferable to use react-jsx, explanation below:


Difference between both

First of all, remember that this option just controls how JSX constructs are emitted in JavaScript files. This only affects the output of JS files that started in .tsx files.

So, the difference between both is just the output of JS files.

Output JS files from Typescript documentation:

Default: "react"

import React from 'react';
export const HelloWorld = () => React.createElement("h1", null, "Hello world");

React 17 transform: "react-jsx"

import { jsx as _jsx } from "react/jsx-runtime";
import React from 'react';
export const HelloWorld = () => _jsx("h1", { children: "Hello world" });

Which is better?

As it is written in the react documentation, in practical terms, the "react" option is just an old way to transform JSX into regular javascript that was not perfect:

  • Because JSX was compiled into React.createElement, React needed to be in scope if you used JSX.
  • There are some performance improvements and simplifications that React.createElement does not allow.

To solve these issues, React 17 introduces new entry points to the React package that are intended to only be used by compilers like Babel and TypeScript.

When you are using "react-jsx" option, you are using this new React 17 compilation.

Therefore, is preferable use "react-jsx" option.

What is the difference between _jsx() and _jsxs()?

There's no difference. Image from jsx-runtime codebase below:

enter image description here

Erick Willian
  • 1,825
  • 11
  • 17