In @types/react, the global JSX namespace has been deprecated:
declare global {
/**
* @deprecated Use `React.JSX` instead of the global `JSX` namespace.
*/
namespace JSX {
...
}
}
Since I enabled ESLint's deprecation/deprecation rules (from the plugin eslint-plugin-deprecation), I now receive an error for function component return type like this:
export default function TestComponent(): JSX.Element { // This JSX is marked as deprecated
return (
<span>Test</span>
);
}
Now that the global JSX namespace has been deprecated, what is the correct return type replacement for JSX.Element in this case?
Is it React.JSX.Element as stated in the deprecation message:
export default function TestComponent(): React.JSX.Element { ... }
Or ReactElement like this:
import { ReactElement } from "react";
export default function TestComponent(): ReactElement { ... }
Or better yet, declare the function component using React.FC and let TypeScript infer the return type, like this:
export const TestComponent: React.FC = () => { ... };
Use
React.JSX.Or import
JSXfrom"react":import {JSX} from 'react'Use
React.ReactElementdirectly (or more accurately,React.ReactElement | null):import { ReactElement } from "react"; export function TestComponent(): ReactElement | null { return ( Math.random() < 0.5 ? null : <> A single Element (could be a Fragment like here) </> ); }This is exactly what (no longer recommended)
React.FCEnforcement:interface FunctionComponent<P = {}> { (props: P, context?: any): ReactElement<any, any> | null; // ... }It is also
JSXElementConstructor:That being said, unless you have some rules that force you to enter a function component return type, you can ignore it for the sake of simplicity:
export function TestComponent() { // ... }Apparently the function can now return anything, Typescript won't complain...unless you try to use it as a functional component in a JSX template, which is the case in fb/cra#8177: