React has long been a go-to JavaScript library and is easily one of the most popular in the world. Also, with popular frameworks like Next.js and Remix being built on top of React and the ability to do mobile development with React-Native, this library is not going away anytime soon. The problem with this however is that most beginners flock to React and start learning it without really understanding how it works. So let’s dive in.
In React, JSX (JavaScript XML) is a syntax that looks similar to HTML but works within JavaScript. It’s not valid JavaScript itself, so React uses a transpiler (usually Babel) to convert JSX into standard JavaScript. This JavaScript code is what the browser ultimately interprets.
When you write JSX, it gets transformed into React.createElement() function calls. These function calls produce React elements, which are the building blocks of a React application. Each element represents a piece of the UI.
Here’s an example of what that looks like:
JSX in a React Component
const element = ();Hello, React!
This is a paragraph.
JSX Transformed into JavaScript:
const element = React.createElement( 'div', null, React.createElement('h1', null, 'Hello, React!'), React.createElement('p', null, 'This is a paragraph.') );
React takes these nested React.createElement() calls and converts them into the corresponding HTML elements in the browser’s DOM.
JSX makes writing React components easier by allowing you to write syntax similar to HTML, but it’s just syntactic sugar for React.createElement() calls that create the structure of your app using JavaScript. This is what allows React to manage the UI efficiently through its Virtual DOM mechanism.
If you enjoyed this article, you might also enjoy my free newsletter I send out every week to developers just like you. You can sign up here.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3