Learn The Web in about a week!
Learning should be fun and quick; no need to spend ages in just one single course.
What exactly is a React node?
Almost everyone knows about React elements but that's not the case with React nodes.
You might've heard of the concept of a React element. It's simply React's abstraction for a DOM element or an instance of a component. But what then is a React node and how does it differ from an element in React? Time for some quick exploration.
What is a React node?
Just like a node is the fundamental unit of the DOM tree (or just about any tree in general), so is a node in the virtual DOM tree in React. A React element (which also represents a component instance) is just one kind of a node; there are many others.
Now, the official documentation doesn't formally define or use the term "React node" mostly anywhere except for on the page describing createRoot().
There it indirectly states what a React node is:
This will usually be a piece of JSX like<App />, but you can also pass a React element constructed withcreateElement(), a string, a number,null, orundefined.
Apart from this, type declarations in the React library label the third parameter of the createElement() function as a rest parameter, each of whose arguments is of type ReactNode.
So inferring from these, a React node is either of the following:
- A React element
- A string
- A Boolean
- A number
undefinednull- An array of these values.
Any other value besides the ones listed above is NOT considered a React node and thus couldn't be used wherever React expects a React node.
React node vs. React element
The difference between a React node and a React element should hopefully be self-evident by now but let's review it quickly.
A React node is any of the values mentioned above that can be used for rendering purposes. A React element, on the other hand, is just one of these possible values — it's simply a type of React node.
Therefore, all elements in React are nodes but not all nodes are elements.