How React.js Uses JSX and Babel to Render Content in the Browser ?
When we build UIs with React, the browser only understands the elements created with React.createElement. However, writing every component with React.createElement(TagName, props, children) can make code harder to write, read and maintain as the codebase grows.
This is where JSX comes into play.
What is JSX?
JSX stands for JavaScript XML, a syntax extension that allows us to write HTML-like code directly in JavaScript. Instead of manually calling React.createElement for each element, JSX lets us define the structure of our UIs in a more readable way.
Here’s an example of JSX code:
const container = <h1>Hello, this is JSX Code!</h1>;
const root = ReactDOM.createRoot(document.querySelector('#root'));
root.render(container);
Why JSX Improves Developer Experience
JSX not only makes code more readable but also brings several advantages:
Recommended by LinkedIn
How JSX is Transformed by Babel ?
While JSX looks like HTML, it’s not something browsers can understand directly. JSX needs to be converted into JavaScript before the browser can interpret it. This is where Babel comes in. Babel is a JavaScript compiler that transforms JSX into standard JavaScript calls, specifically into React.createElement functions.
Behind the Scenes of JSX
When Babel processes the JSX code from the example above, it converts it to JavaScript that looks like this:
const container = /*#__PURE__*/React.createElement("h1", null, "Hello This is JSX Code ");
const root = ReactDOM.createRoot(document.querySelector('#root'));
root.render(container);
In this converted code, React.createElement("h1", null, "Hello, this is JSX Code!") creates a plain JavaScript object that represents the <h1> element. This object can then be rendered by React.
Understanding the Role of ReactDOM and Rendering
After Babel transforms JSX into React.createElement calls, React's ReactDOM library takes over. ReactDOM is responsible for Creating a Root Node and Rendering Components.
This flow of JSX and Babel is what allows us to write clean, intuitive UI code in React!
Conclusion:
In summary, JSX simplifies the process of building UIs in React by allowing developers to write HTML-like syntax directly in JavaScript. Babel converts this JSX into JavaScript that browsers can understand, while ReactDOM takes care of rendering the components. By using JSX, developers can create more readable and maintainable code, making the development experience smoother and more efficient.
Full-Stack web developer | MCA with Full stack web development | BCA Graduate
6moInterested