Lesson 7 - JSX and How React Treats the DOM & JSX Compilation(by Babeljs) - Overview
Last updated
Last updated
What is JSX?
JSX stands for JavaScript XML. It's a syntax extension to JavaScript that allows you to write HTML-like code within your JavaScript files.
Enhanced Readability: JSX makes your component structure more visually intuitive and easier to read, particularly for developers familiar with HTML.
Simplified DOM Manipulation: JSX abstracts away the complexities of directly manipulating the DOM (Document Object Model), making it easier to build and update UI elements.
JSX vs. Compiled JavaScript
The image illustrates the transformation process:
JSX Code (Human-Readable):
You write JSX code using HTML-like syntax within your JavaScript files.
For example: const element = <h1 className="greeting">Hello, world!</h1>;
JSX Compiler (Babel):
Before the browser can understand and execute your code, the JSX code needs to be converted into plain JavaScript.
Babel is a popular JavaScript compiler that handles this transformation.
Compiled JavaScript (Browser-Understood):
Babel converts the JSX code into calls to React.createElement()
.
This function creates a JavaScript object representing the HTML element.
React's Approach to the DOM
The image illustrates the difference between traditional DOM manipulation and how React handles it.
Traditional DOM Manipulation:
Direct Manipulation: Developers directly interact with the DOM using JavaScript methods like getElementById()
, setAttribute()
, createElement()
, appendChild()
, etc.
Performance Overhead: Each change to the DOM triggers a costly process of re-rendering and updating the entire page or the affected parts. This can lead to performance issues, especially in complex applications.
React's Virtual DOM:
Virtual Representation: React creates a virtual representation of the actual DOM in memory. This virtual DOM is an efficient JavaScript object that mirrors the structure of the actual DOM.
Efficient Updates: When data changes in a React component, React updates the virtual DOM. Then, React compares the virtual DOM with the actual DOM and identifies only the specific changes that need to be made.
Minimal DOM Manipulation: React only updates the actual DOM with the minimal set of changes required, which significantly improves performance.
In essence, React's virtual DOM acts as an intermediary between your component code and the actual DOM. This approach allows React to optimize the rendering process and make updates efficiently, resulting in a faster and more responsive user experience.
Key Points Illustrated in the Image:
The image highlights the traditional DOM manipulation methods with comments explaining their purpose.
It contrasts this with the React approach, emphasizing the use of a virtual DOM for efficient updates.
Click "Try it out" menu
Example
Babaljs site :