React Element vs JSX Element vs React Node vs React Component
React
20/03/2023
Even for experienced React developers, the difference between a React/JSX Element, Node and Component can be somewhat elusive at first. So here's a clear breakdown of the terms.
React Element
A React Element is the smallest building block of a React application and is an object representation of a virtual DOM node. The creation of elements are cheap and are done as follows.
// React.createElement(type, [props], [...children])const element1 = React.createElement( "div", { className: "italic" }, "Basic Element")const element2 = React.createElement(CustomButton, { color: "red" }, null)
The first argument of the createElement
method describes the type of the element. It can either be a tag name (such as 'div' or 'span'), a React component or a React fragment. The 2nd argument are the props of the element while the 3rd its children.
In the end, createElement
returns a plain JavaScript object that describe a virtual DOM node, which is not to be confused with a regular DOM node. For instance, element1
returns:
console.log(element1)
/** * { * $$typeof: [object Symbol] { ... }, * _owner: null, * _store: { ... }, * key: null, * props: { * children: "Basic Element", * className: "italic" * }, * ref: null, * type: "div" * } **/
JSX Element
A JSX Element is really nothing else than syntactic sugar for createElement
. The 2 previous examples can be rewritten with JSX, which ultimately results in the same thing, i.e. plain JavaScript objects.
const element = <div className="italic">Basic Element</div>const element = <CustomButton color="red" />
React Component
A React component is a function that returns one or more React Elements. Nothing more, nothing less.
const Text = ({ children }) => ( <div className="italic"> <p>{children}</p> </div>)
However, once we "call" this component using JSX syntax, it's actually an Element of type React component.
<Text>Greetings!</Text>// Which is the same as React.createElement(Text, null, "Greetings!")
React Node
Lastly, a React Node is a more general term for anything that is returned by a component, which may be more than an Element. React nodes may be:
- A React element created like
<div />
orcreateElement('div')
- A portal created with
createPortal
- A string
- A number
true
,false
,null
, orundefined
(which are not displayed)- An array of other React nodes
const Number = () => <div>Woah! {[1, "world", true]}</div>// This return statement of `Number` is considered a React node.