This is the 31st day of my participation in the August Text Challenge.More challenges in August

What is JSX?

Before we start, let’s look at a bit of code

const element = <h1>Hello, world!</h1>;
Copy the code

If you look at this code, it says it’s HTML but it’s not HTML but it uses HTML tags, it says it’s a string but it doesn’t have single quotes or double quotes, so it’s not a string. This interesting piece of code is called JSX, and it is a JavaScript syntactic extension that stands for JavaScript and Xml. 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.

Why use 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 does not use the artificial separation of markup and logic into separate files. Instead, it separates concerns by storing both together in loosely coupled pieces of code called “components.” We will learn more about components in later chapters.
  • React doesn’t mandate the use of JSX, but most people find it visually helpful when putting JSX and UI together in JavaScript code. It also enables React to display more useful error and warning messages.

With that out of the way, let’s start learning about JSX!

Embed expressions in JSX

Let’s start with a piece of JSX code

const name = "Alvin"
const element = <h1>Hello, {name}</h1>;
ReactDOM.render(
	element,
	document.getElementId('root'));Copy the code
  • In the above code, we declared a variable named name and then used it in JSX. Note here that the name we introduced in JSX is wrapped in braces. This is a syntactic requirement of JSX that some variables must be wrapped in braces if they are to be used.
  • In JSX syntax we can place any valid JavaScript expression inside curly braces. For example, 2+2, user.firstName, or formatName(user) are valid JavaScript expressions
  • Although JSX can use JavaScript expressions wrapped in braces, objects cannot be used directly inside braces, except in some special cases, such as when we wanted to use {=={name:”Alvin”==}} in JSX syntax, which is not allowed and throws errors directly
const element = <h1>Hello, {{name:"Alvin"}}</h1>// This syntax is not allowed and will result in an error
Copy the code
  • For example, if we want to use inline style= “XXX” inside the tag, the object wrapped in braces must be an object, otherwise it will report a syntax error
const element = <h1 style={{color:'red'}} >Alvin</h1>
Copy the code
  • In JSX syntax, in addition to embedding JavaScript variables and object attributes, you can also directly insert function calls into braces. Note that the function must return the result
let user = {
	firstName: 'Alvin'.lastName: 'Li'	
};
function getFullName(user){
 return user.firstName + ' ' + user.lastName;
}
const element = <h1>Hello, {formatName(user)}</h1>!
ReactDOM.render(
  element,
  document.getElementById('root'))Copy the code

JSX specific attributes

  • In JSX syntax, you can add custom attributes to tag elements, which can be quoted strings or JavaScript expressions wrapped in braces
  • When embedding JavaScript expressions in attributes, you cannot use both quotation marks and braces for the same attribute, that is, you can only use either quotation marks (for string values) or braces (for expressions) for the same attribute. Enclosing quotation marks around braces is not allowed
const element = <div tabIndex="0"></div>
const img = <img src={user.photo}></img>
Copy the code
  • Also: Because JSX is syntactically closer to JavaScript than HTML, ReactDOM uses camelCase naming to define attribute names. For example, the class in JSX becomes className, and tabIndex becomes TabIndex.

Use JSX to specify child elements

  • In JSX, we can use a single closed tag if there is no content inside the tag
  • Of course, JSX tags can also contain multiple nested descendant tags, then need to use double closed tags
const element  = <img src={user.photo} /> // Close the label
// Double close label
const body = <div>
  <h1>Hello</h1>
  <h2>Good morning world</h2>	
</div>
Copy the code

JSX prevents injection attacks

In JSX we can safely use user input because ReactDOM escapes by default before rendering all input. It ensures that you never inject anything in your application that you didn’t explicitly write. All content is converted to a string before rendering. This can be an effective way to XSS attack

const element = "<script>alert('hahahha')</script>"
Copy the code

The script in the above code is not recognized as valid JavaScript code, but is escaped as string output

JSX represents an object

  • In the last article, we introduced a Babel library when react was introduced. In addition to converting ES6 syntax to ES5, Babel also translates JSX into a function called react.createElement ().
  • React.createelement () does some checking up front to help me write error-free code
/ / way
const element = <h1 className="greeting">Hello, world!</h1>;
2 / / way
const element2 = React.createElement("h1", {className:'greeging'}, 'Hello, world! ');
Copy the code

The above two examples of code are exactly equivalent, even though we wrote code in mode 1, it will eventually be converted to mode 2.

  • Instead, react.createElement () creates one of these objects
const element = {
  type: 'h1'
	props: {
		className: 'greeting'.children: 'Hello, world! '}};Copy the code
  • These objects are called React elements. What do we want to see on screen, what we call a virtual DOM, and React then reads those objects and builds them into a real DOM and keeps them up to date.

Eight, this chapter summary

  • This chapter introduces what JSX is and why JSX is used in React
  • Basic syntax used by JSX
  • Definition of JSX attributes
  • Nesting of JSX child elements
  • Anti-injection attack of JSX
  • React JSX (convert to React object)