score:507
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. component
s 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.
score:4
https://github.com/typescript-cheatsheets/react#useful-react-prop-type-examples
export declare interface appprops {
children1: jsx.element; // bad, doesnt account for arrays
children2: jsx.element | jsx.element[]; // meh, doesn't accept strings
children3: react.reactchildren; // despite the name, not at all an appropriate type; it is a utility
children4: react.reactchild[]; // better, accepts array children
children: react.reactnode; // best, accepts everything (see edge case below)
functionchildren: (name: string) => react.reactnode; // recommended function as a child render prop type
style?: react.cssproperties; // to pass through style props
onchange?: react.formeventhandler<htmlinputelement>; // form events! the generic parameter is the type of event.target
// more info: https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#wrappingmirroring
props: props & react.componentpropswithoutref<"button">; // to impersonate all the props of a button element and explicitly not forwarding its ref
props2: props & react.componentpropswithref<mybuttonwithforwardref>; // to impersonate all the props of mybuttonforwardedref and explicitly forwarding its ref
}
score:5
reactelement is the type for elements in react, either created via jsx or react.createelement.
const a = <div/> // this is a reactelement
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.
const a = (
<div>
hello {[1, "world", true]} // this is a reactnode
</div>
)
jsx.element
is an internal hook for typescript. it is set equal to reactelement to tell typescript that every jsx expressions should be typed as reactelements. but if we'd use preact, or other technologies using jsx it would be set to something else.
functional components return reactelement | null
, so it cannot return a bare string or an array of reactelements. it is a known limitation. the workaround is to use fragments :
const foo: fc = () => {
return <>hello world!</> // this works
}
class components' render function return reactnode
, so there shouldn't be any problem.
score:70
1.) what is the difference between jsx.element, reactnode and reactelement?
reactelement and jsx.element
are 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
withrender()
, more permissive than react/jsts 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
some options:3.) how do i solve this with respect to null?
// 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 needed
const 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` type
const 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.
const mycompfragment: functioncomponent = () => <>"hello"</>
const mycompcast: functioncomponent = () => "hello" as any
// alternative to `as any`: `as unknown as jsx.element | null`
Source: stackoverflow.com
Related Query
- When to use JSX.Element vs ReactNode vs ReactElement?
- Cannot use JSX unless the '--jsx' flag is provided when "jsx" is "react-jsx"
- When to use anonymous functions in JSX
- How to use useRef when element is inside condition?
- React+gsap use random animation element group can't work when it complete?
- Getting "JSX element type 'App' does not have any construct or call signatures." ts(2604) error when exporting array of JSX Element
- Why does a React JSX element event handler not use parentheses similar to a html event handler?
- How to get next element in Immutable List when use .map?
- JSX element type 'AddIcon' does not have any construct or call signatures when testing
- How to clear/destroy Chart.js canvas when the chart is represented as a react JSX element
- React JSX expressions must have a parent element error when adding a second <div>
- When we use JSX <div></div>, or React.createElement("div", ...), is this virtual DOM (element)?
- When I try to push an element to a array but it takes only one rest of the elements are got removed automatically. It happen when use useState hook
- How can I use an SVG element created with JSX as an image source in a Canvas?
- Getting 'Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag' even when I use React.Fragment
- Why React fails to render changes in array of JSX element when using .map index as a key?
- How do we use two themes on the same DOM element when using a ThemeProvider?
- React complains element type is invalid when trying to use context
- 'React' must be in scope when using JSX but I do not use ESLint
- Ionic React Typescript with pug.js, 'Uncaught ReferenceError: React is not defined' when use tsx but not jsx
- when to and when not to use "this" in JSX event handler function reference?
- In react I had created wrapper components.So now i need to use them in my app.tsx in element parameter which is in route tag.But error as not jsx elem
- How to use .contains(nodeOrNodes) API when the contained react element has an arrow function event handler?
- Make hover effect stick in an element when mouse is pointed to adjacent element in React Jsx
- When to use ES6 class based React components vs. functional ES6 React components?
- Cannot use JSX unless the '--jsx' flag is provided
- 'React' must be in scope when using JSX react/react-in-jsx-scope?
- React Context vs React Redux, when should I use each one?
- When to use React setState callback
- react-router vs react-router-dom, when to use one or the other?
More Query from same tag
- how to fix warning with React and babel: Parsing error: Unexpected token <
- how to add code more in react to hide and show pages when I click again
- execute child_process in a electron + react application
- Check if an element is in the viewport but with mapped refs - ReactJS
- How do I map over an array of objects in React and then conditionally render a component based on a previous value?
- how to add global scss styles to preact app
- Getting typescript errors with any
- How to trigger a state change when hovering over an element
- why doesn't validating input on eventListener work?
- When does create-react-app obfuscate or minify code?
- Using useEffect to get data from an api
- React components not rendered on url change with React Router
- Facing Error When Linking A Library With React Native
- Redirect refs from children component to the parent in ReactJs
- How can i use module.exports.function in es6?
- Change state hook being called the second time function is called
- Creating a parent 'workspace' component in ReactJS
- React Hook "useEffect" is called conditionally, in supposedly simple get-display-retrieve inputs component
- React state is called before receiving value from API
- Axios not returning data to rootSaga
- React event onMouseLeave not triggered when moving cursor fast
- How I show value of an input inside a span tag in the form of typing effect?
- Maximum update depth with useState to array from map
- How to wait until function returns a value?
- React Typescript: text translation file with JSX
- how to return response of axios in return
- Too many re-renders. React limits the number of renders
- Material UI form validation issues
- Is there a better way to split the reducers to smaller pieces?
- TypeError: Cannot read property 'preventDefault' of undefined in React