I am currently migrating a React application to TypeScript. So far, this works pretty well, but I have a problem with the return types of my render functions, specifically in my functional components.
I have always used JSX.Element as the return type, now this doesn’t work any more if a component decides to not render anything, i.e. returns null, since null is not a valid value for JSX.Element. This was the beginning of my journey. I searched the web and found that you should use ReactNode instead, which includes null and a few other things that can happen.
However, when creating a functional component, TypeScript complains about the ReactNode type. Again, after some searching I found, that for functional components you should use ReactElement instead. However, if I do so, the compatibility issue is gone, but now TypeScript again complains about null not being a valid value.
To cut a long story short, I have three questions:
What is the difference between JSX.Element, ReactNode, and ReactElement?
Why do the render methods of class components return ReactNode but functional components return ReactElement?
How do I solve this with respect to null?
What is the difference between JSX.Element, ReactNode andReactE element?\n\nA ReactElement is an object with type, props, and key properties: interfaceReactIlement P = any, T extends | string | JSXÉlementConstructorany> = string — > type: T; prop: P; key: string: null; .\n\nA JSX.Element is a ReactIlementany, any>. It is one of the libraries that implements jjXX in their own way: declare global // … namespace JEWSX – . …. interface Element extends Reacted.ReactAIIany , Any> : ; ?\n\nA ReactPortal with a children property: Interface reactportal extends ReactionElement children: ReactedNode; .\n\nA ReactNode (reactElement, string, number, IterableReactII) is: \’It\’s an undefined, boolean and reactedPortal\’ (likely called a REactNelement), IactFile | string | number | iterability | | bl | null, or .\n\ndiv> // (- ReactElementComponent>) // ‘It’s ‘reactIlement && ’text’ // I’m ‘advanced’ to ‘ReactNode ‘/Com component> .\n\nWhy do the render methods of class components return ReactNode, but function elements return reactElement?\n\nThis is for historical reasons.’ A ReactNode: class ComponentP, S> // . … render(): Reactor Node; // (… ).\n\nA FunctionComponent returns a ReactElementany, any> | null: interface Function FunctionP> (props: PropsWithChildrenPP>, context? Any): WeakValidationMapProps.: \’WeakVALId>> > >1p>; weakTagTags; OurakViewView P> = = (undefined); contextTableTable; DefaultDefaults?\n\nHow do I do this respectfully to null?\n\nType it as ReactElement | null, as is the case with Reacted. Or let TypeScript mean the type.