When to use JSX.Element vs ReactNode vs ReactElement? When to use JSX.Element vs ReactNode vs ReactElement? javascript javascript

When to use JSX.Element vs ReactNode vs ReactElement?


What is the difference between JSX.Element, ReactNode and ReactElement?

A ReactElement is an object with a type and props.

 type Key = string | number interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {    type: T;    props: P;    key: Key | null;}

A ReactNode is a ReactElement, a ReactFragment, a string, a number or an array of ReactNodes, or null, or undefined, or a boolean:

type ReactText = string | number;type ReactChild = ReactElement | ReactText;interface ReactNodeArray extends Array<ReactNode> {}type ReactFragment = {} | ReactNodeArray;type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

JSX.Element is a ReactElement, with the generic type for props and type being any. It exists, as various libraries can implement JSX in their own way, therefore JSX is a global namespace that then gets set by the library, React sets it like this:

declare global {  namespace JSX {    interface Element extends React.ReactElement<any, any> { }  }}

By example:

 <p> // <- ReactElement = JSX.Element   <Custom> // <- ReactElement = JSX.Element     {true && "test"} // <- ReactNode  </Custom> </p>

Why do the render methods of class components return ReactNode, but function components return ReactElement?

Indeed, they do return different things. Components return:

 render(): ReactNode;

And functions are "stateless components":

 interface StatelessComponent<P = {}> {    (props: P & { children?: ReactNode }, context?: any): ReactElement | null;    // ... doesn't matter}

This is actually due to historical reasons.

How do I solve this with respect to null?

Type it as ReactElement | null just as react does. Or let Typescript infer the type.

source for the types


1.) What is the difference between JSX.Element, ReactNode and ReactElement?

ReactElement and JSX.Elementare the result of invoking React.createElement directly or via JSX transpilation. It is an object with type, props and key. JSX.Element is ReactElement, whose props and type have type any, so they are more or less the same.

const jsx = <div>hello</div>const ele = React.createElement("div", null, "hello");

ReactNode is used as return type for render() in class components. It also is the default type for children attribute with PropsWithChildren.

const Comp: FunctionComponent = props => <div>{props.children}</div> // children?: React.ReactNode

It looks more complicated in the React type declarations, but is equivalent to:

type ReactNode = {} | null | undefined;// super type `{}` has absorbed *all* other types, which are sub types of `{}`// so it is a very "broad" type (I don't want to say useless...)

You can assign almost everything to ReactNode. I usually would prefer stronger types, but there might be some valid cases to use it.


2.) Why do the render methods of class components return ReactNode, but function components return ReactElement?

tl;dr: It is a current TS type incompatibility not related to core React.

  • TS class component: returns ReactNode with render(), more permissive than React/JS

  • TS function component: returns JSX.Element | null, more restrictive than React/JS

In principle, render() in React/JS class components supports the same return types as a function component. With regard to TS, the different types are a type inconsistency still kept due to historical reasons and the need for backwards-compatibility.

Ideally a valid return type would probably look more like this:

type ComponentReturnType = ReactElement | Array<ComponentReturnType> | string | number   | boolean | null // Note: undefined is invalid

3.) How do I solve this with respect to null?

Some options:
// Use type inference; inferred return type is `JSX.Element | null`const MyComp1 = ({ condition }: { condition: boolean }) =>    condition ? <div>Hello</div> : null// Use explicit function return types; Add `null`, if neededconst MyComp2 = (): JSX.Element => <div>Hello</div>; const MyComp3 = (): React.ReactElement => <div>Hello</div>;  // Option 3 is equivalent to 2 + we don't need to use a global (JSX namespace)// Use built-in `FunctionComponent` or `FC` typeconst MyComp4: React.FC<MyProps> = () => <div>Hello</div>;

Note: Avoiding React.FC won't save you from the JSX.Element | null return type restriction.

Create React App recently dropped React.FC from its template, as it has some quirks like an implicit {children?: ReactNode} type definition. So using React.FC sparingly might be preferable.

In edge cases, you can add a type assertion or Fragments as workaround:
const MyCompFragment: FunctionComponent = () => <>"Hello"</>const MyCompCast: FunctionComponent = () => "Hello" as any // alternative to `as any`: `as unknown as JSX.Element | null`