Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a component's render method have return type React.ReactNode or JSX.Element?

Tags:

Both seem to result in no compilation errors, but what's the difference and is one preferable to the other?

like image 562
xli Avatar asked Feb 05 '19 23:02

xli


People also ask

What is the difference between JSX element and ReactNode?

ReactNode is wider, it can be text, number, boolean, null, undefined, a portal, a ReactElement, or an array of ReactNodes. It represents anything that React can render. JSX. Element is an internal hook for Typescript.

What is the return type of render in React?

Regardless of what a component ends up rendering, React. createElement always returns an object, which is the JSX.

What does render method return?

"The render method returns a description of what the DOM should look like, and then React efficiently updates the real DOM to match."

Is it mandatory for each React component to have a render () function?

render() The render() method is the only required method in a class component.


2 Answers

This exact question was asked over in the react-typescript-cheatsheet repo issue #57

To quote the original answer:

Regardless of what a component ends up rendering, React.createElement always returns an object, which is the JSX.Element interface, but React.ReactNode is the set of all possible return values of a component.

  • JSX.Element -> Return value of React.createElement
  • React.ReactNode -> Return value of a component

Generally, I think the idea is that JSX.Element specifically describes the interface of React.createElement and is narrow in scope whereas React.ReactNode is more broad and covers all possible values that a Component could return.

like image 126
Aaron Avatar answered Sep 24 '22 02:09

Aaron


It depends. ReactJS in principle can render:

type RenderType = JSX.Element* | Array<RenderType> | string | number | boolean | null // * includes Portal, Fragment // for both function and class components // (type doesn't exist in React type declarations) 

TS render types are currently limited to:

  • Class component: ReactNode (wider than permitted by React)

  • Function component: JSX.Element | null (more restrictive than React)

JSX.Element is more or less the same as ReactElement, you can use both interchangeably.

like image 22
ford04 Avatar answered Sep 23 '22 02:09

ford04