In this Chapter we gonna look at, what are React Elements, how do we create Elements
in React and how React create Elements under the hood.
Elements are the smallest building blocks of React apps. An element describes what
should be there in our user interface. An Element is a plain object describing what we
want to appear in terms of the DOM nodes.
Creating a React Element is Cheaper compared to creating a DOM element directly.
An Element can be created by using JSX or directly using React without JSX. Lets see how to create
an Element using JSX, to learn more about JSX open Introduction to JSX file. for more detailed
explaination.
const reactElementUsingJSX = <h1>Hello, world!</h1>;
const reactElementWithoutJSX = React.createElement("h1", null, "Hello, world!");
Creating an element in JSX looks pretty simple, self-explanatory, and straightforward. But let's look at
React.createElement and all the parameters / arguments it takes.
-
First parameter, if you look at it is "h1". This first parameter is a type of element that you want to create for example it's "h1" in this particular example, but you can pass stuff like "div" "img" etc.
-
Second parameter is "null" in this example but that's not always the case. This second
parameter is an object full of properties / attributes that you have provided to that
eleemnt. for example className, tabIndex etc. let's look at example.const reactElementUsingJSX = <h1 className="greet">Hello, world!</h1>;
const reactElementWithoutJSX = React.createElement( "h1", { className: "greet", ... }, "Hello, world!" );
-
The third parameter is anything that you want to pass to the innerHTML element you created. it can
be any JavaScript valid expression, string etc.
Using react without JSX is something which is not recommand, but is good to understand how it works
under the hood. React uses babel under the hood to transpile or compile our JSX code to regular JavaScript.
To discover more checkout babel here. https://babeljs.io/repl