This is a series of post on how to write react-like-library from scratch.
Please read the previous posts if you haven't already.
Chapter 1 => Project Setup and createRoot function
JSX is a powerful syntax extension to JavaScript that allows you to write HTML-like code in your JavaScript files.
But browsers don't understand JSX directly, so it needs to be compiled into plain JavaScript.
In this blog post, I'll show you how we can compile JSX to JS.
Let's get started!
See the below component which is written in JSX
.
const Component = (props) => {
return <div id="root">Hello world</div>;
};
if you were to run this code in the browser, you would get an error saying that JSX
is not defined.
This is because browsers don't understand JSX
directly, so it needs to be compiled into plain JavaScript
.
if you were to run this with the Actual React library, it would work fine.
the above code is equivalent to the following code
const Component = (props) => {
return React.createElement('div', {id: 'root'}, 'Hello world');
};
But how does this work?
Either we need to compile JSX
to js using babel
or any other tool or we can write our own version of a JSX
parser that can turn a JSX “component” into a JavaScript
one that returns valid HTML
.
for this, let's use babel
to compile JSX
to js so that we can focus on writing other main features of react-like-library.
we also need to createElement
function to create element from JSX
.
What we get back from a React.createElement
call is actually a simple object that describes the element you want to create
const element = {
type: 'div',
props: {
id: 'root',
children: 'Hello world',
},
};
It has a type property that tells you what kind of element it is (in this case, a div), and it has a props property that contains all the attributes you want to set on the element.
Finally, it has a children property that contains all the children of the element
we will cover how to write createElement from JSX in the coming chapters.
we will also discuss how we can compile JSX to js using babel or any other tool.
Happy Learning!
All the codes are available in the following GitHub repository
github.com/nishammahsin/react-like-library/..2