React Basics You Should Know
Let's begin with understanding how to create elements in React using the React.createElement method.
As we can see in the example below, the element nested is essentially a virtual representation of a nested HTML structure. In this case, a
element as its child.
In React, we create such elements using:
React.createElement('type of tag', { attributes like 'id', 'className' }, children);
Now, what do you think will happen if we console.log(heading)?
You might guess that it will print an actual HTML element—but in reality, it logs a JavaScript object that represents that element. This object is what React uses to manage and render the UI efficiently.
All of this abstraction is handled behind the scenes by React.
Here’s an example (App.js):
const nested =
React.createElement(
'div',
{ id: 'parent' },
React.createElement('h1', { id: 'child' }, 'This is child')
);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(nested);
JSX Introduction
While **React.createElement **is useful to understand what happens behind the scenes, writing complex UIs using it can quickly become verbose and hard to read. This is where JSX comes in.
JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to HTML. It allows you to write UI elements in a more intuitive and readable way.
Here’s the same example using JSX:
const nested = (
This is child
);
Under the hood, this JSX code is compiled to the same **React.createElement **call you saw earlier:
React.createElement(
'div',
{ id: 'parent' },
React.createElement('h1', { id: 'child' }, 'This is child')
);
Using JSX makes your code cleaner, especially when you start building components with multiple nested elements.