A React element is a JavaScript object describing a DOM node (HTML element) and its properties.
There are two ways to create a React element: the createElement
method and the JSX method. The JSX method is more common.
Here is an example of a simple React component using JSX:
JSX is used in the return statement of a React component. It is a syntax extension to JavaScript that allows us to mix JavaScript with HTML. We will explore the rules of JSX in shortly. It is important to note that JSX is not valid JavaScript. It is transformed into React.createElement
calls during the build process.
createElement
methodHere is the same example using the createElement
method:
Notice the return statement uses the React.createElement
method. The first argument is the type of element (in this case, a string representing an HTML element). The second argument is an object containing the element’s properties (or null
if there are none). The third argument is the content of the element.
The general syntax of React.createElement
follows this pattern:
The createElement
method is not commonly used because JSX is more readable and easier to write. However, it is important to understand how JSX is transformed into React.createElement
calls.