This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021
React developers are familiar with JSX. JSX has been around React for a long time.
What is the JSX
JSX is a syntax extension to JavaScript. We recommend using JSX with React. JSX is a good way to describe how the UI should behave as it should interact. JSX may be reminiscent of a template language, but it has all the functionality of JavaScript.
JSX is not mandatory in React, if not
class Hello extends React.Component { render() { return React.createElement( 'div', null, 'Hello World' ); }}Copy the code
Use the JSX
class Hello extends React.Component { render() { return <div>Hello World</div>; }}Copy the code
Through the above code comparison, it can be clearly seen that the code written by JSX is more concise and the code hierarchy is clearer
Although written using JSX, the essence is still react.createElement
Why not just use React. CreateElement?
When we define a slightly more complex DOM structure
const ele = <div>
<p>Hello World</p>
<p>I' Nordon</p>
</div>;
Copy the code
The above code corresponds to the react. createElement code
const ele = React.createElement(
"div",
null,
React.createElement(
"p",
null,
"Hello World"
),
React.createElement(
"p",
null,
"I' Nordon"
)
);
Copy the code
By comparison, using react. createElement to nest code structures is more complex, not only less readable, but also a worse development experience during writing
JSX syntactic sugar allows developers to create virtual DOM using htML-like tag syntax that we are most familiar with, reducing learning costs and improving r&d efficiency and experience
Why JSX?
React argues that rendering logic is intrinsically coupled to other UI logic, such as binding events in the UI, notifying the UI when state changes at certain moments, and displaying prepared data in the UI.
React and JSX provide more friendly error and warning messages and higher security
React processes content before rendering, ensuring that the rendered content is written by the developer. This protects against XSS attacks. For example, it translates & to amp;
Some common translations
< translated as < > < span style = "max-width: 100%; "Translated as"; 'translates to 'Copy the code
JSX is a syntactic extension of JS that allows developers to write business logic freely in JSX
function getInfo(person) {
return `I'm ${person.name}, age is ${person.age}`;
}
const person = {
name: 'Nordon',
age: 18
};
const element = (
<h1>
Hello, {getInfo(person)}!
</h1>
);
ReactDOM.render(
element,
document.getElementById('root')
);
Copy the code