preface

In the era of Jq and native javascript, when writing a page, it is often emphasized that content structure, cascading style, behavior and action should be separated. The division of labor among the three is clear, and they should not be coupled together

However, after React came into being, everything was JS. At first, IT was very annoying to write HTML code in JS, and even violated the original principle

However, there is no logical separation from the original, which merely managed the three language technologies separately in three different file locations

Since the front-end UI display is HTML,CSS,javascript, so the implementation of a function of all the code in a file management, is also a macro code encapsulation, modular processing.

Using JSX isn’t a step backwards, it’s just a syntactic sugar, and while it’s not mandatory in React, it’s officially recommended.

Because having JSX and UI together in javascript code is visually helpful, it also enables React to display useful errors and warnings

Now let’s learn about JSX. When you get used to it, you won’t turn your nose up at it, but you’ll love it

Click the link for a better reading experience

React Learn (2)- Simple JSX- Video content

What is JSX?

Full name: javascript and XML

Definition: Extensible (custom) markup language, based on javascript, incorporating XML, we can write XML in JS, and using JSX is a good way to describe how the UI should interact on the page

The following is a common label that is provided unofficially, but a special label that is defined by the user

<person>
       <name></name>
       <age></age>
       <height></height>
       <weight></weight>
</person>
Copy the code

In fact, you can call these custom tags components, parts of the page, with independent functionality and logic. React JSX implements componentization

After initializing a react application with the create-react-app scaffolding, the last line of code in the index.js entry file, reactdom.render (), is the first argument to the function call < app />

import React from 'react'; // Use the react.js library to instantiate the react object import ReactDOM from with the import keyword definition'react-dom'; <App />, document.getelementByid (<App />, document.getelementByid ('root'))
Copy the code

To better understand this, you can change the code to the following in index.js

const element = <App />;
const container = documnent.getElementById("root");

ReactDOM.render(element, container);
Copy the code

ReactDOM is an instance object of the React-DOM, which is used to convert the virtual DOM to the real DOM. A render method under the ReactDOM instantiation object takes two actual parameters, the first is the component to render, and the second is the mount point of the component to render to Where, in this case, is rendering to the root node

Reactdom.render (component to render, location to mount component);Copy the code

JSX:

const element = <h1 title="H1 tags">Hello,itclanCoder</h1>'h1',{title:"H1 tags"}, "hello, itclanCoder"); // react.createElement () will perform some checks beforehand to help you create such an object, but in practice it will not. Var Element = {type: 'h1',
   props: {
   title: "H1 tags",
   children: "hello,itclanCoder"}}Copy the code

These objects are called React elements. They describe what you want to see on the screen. React reads these objects and then uses them to build the DOM and keep it up to date. Note:

  • React doesn’t have a template language (like Vue’s Template), but it does have all the functionality of JavaScript

  • You can write XML(HTML) in JS with only one top-level element. You can also use the React Fragment(or placeholder) component to wrap your JSX child elements, including child nodes and interpolation expressions.

  • For ease of reading, the JSX content returned by the return is wrapped in parentheses () to break JSX into multiple lines. This is not mandatory, but it avoids the auto-insert semicolon trap shown in the following code:

import React from "react";
import ReactDOM from "react-dom";


class Acomponent extends React.Component {
    render() {
// returnFollowed by parentheses, just for line breaks, the top layer of the root node can only be one elementreturn (
       <div>
         <h1 title="I'm Chuan Chuan."</h2> </div>)}} // Use the Fragement placeholder component provided by React, but import React first. { Componnet, Fragment } from"react";
import ReactDOM from "react-dom";

class Acomponent extends Component {
  render() {
    return (
     <Fragment>
        <h1 title="I'm Chuan Chuan."</h1> </h2> </Fragment>}}Copy the code

Let’s see how JSX is used

Specific use of JSX

  • Embedding expressions in JSX {expressions}

Double braces can contain variables, strings, arrays, function calls, but cannot be objects. If and for statements are not supported

For example, if you write an object in an interpolation: it will report an error

{ {name: "Chuan chuan", age: "A cute '90s guy in the front row."}}Copy the code

The error message is as follows:

Objects are not valid as a React child (found: object with keys {name, age}). If you meant to render a collection of children, use an array instead
Copy the code

Object invalid as React child object (find: object with key {name, age}) If you want to render subcollections, use arrays

Of course, if it is an array, it is automatically concatenated, essentially as a result of the join(“”) method in the array

{["Chuan chuan"."The most handsome man in the universe."} // Chuan Chuan is the most handsome in the universeCopy the code

Of course, if in JSX, the for statement will also report an error

<li>
 {
   if(this.isBtn) { <Button />
 }
</li>
Copy the code

JSX is also an expression that does not support if for statements, but it can be used in the code block of the if for loop, assigning JSX to variables, passing JSX as an argument, and returning JSX from functions

function getMessage(user) {
  if (user) {
    return<h1>Hello, { formatName(user) }! </h1>; }return<h1>Hello, itClanCoder.</h1>; } `Copy the code

Note: Boolean types, Null, and Undefined are ignored. False, Null, Undefined, and true are valid child elements. But they don’t get rendered. The following JSX expressions render the same:

<div />

<div></div>

<div>{ false }</div>

<div>{ null }</div>

<div>{ undefined }</div>

<div>{ true }</div>
Copy the code

How it works: This helps render other React elements under certain conditions. For example, in the following JSX, is rendered only if isBtn is true

<div>
  { isBtn && <Button /> }
  <Content />
</div>
Copy the code

One thing to note is that some false values, such as the number 0, will still be rendered by React, as shown below

<div>
{
  this.aBtns.length &&
  <Button content="I am the button." />
}
</div>
Copy the code

To solve this problem, make sure that the expression before && is always a Boolean

Otherwise, if you want to render false, true, null, undefined values, you need to convert them to strings first:

There are three ways to convert strings

  • Object. ToString (), note that this method does not apply to objects whose data type is null and undefined

  • Concatenate with empty strings :variable+’ “; This method is common, but not very readable

  • Use String(variable): Use the String object method to convert. This method is recommended

<div> <p> object.toString() {myvariable.tostring ()}</p> <p> Concatenate {myVariable + with empty string' '} < / p > < p > in String (variable) {String (myVariable)} < / p > < / div >Copy the code

Of course, variables in interpolation can also be quoted as in Es6

hello, { `${String(false)}` } // false
Copy the code

Now let’s take a look at the principles of JSX. With this in mind, you will know how a JSX works and how it renders to a page

JSX principle

The DOM element structure of a page can be described using javascript objects, including information such as tag names, attributes, child elements, and event objects

In JS, everything is the object, the characteristics of the object is, contains attributes or methods, in fact, anything, can be described with the object

For example, the following JSX structure

<div class="input-wrap">
  <input 
     type="text" 
     autocomplete="off" 
     value="" 
     id="mq" 
     class="input" 
     title="Please enter search words."</button> </div>Copy the code

Describe the above information in terms of objects:

{
  tagName: 'div',
  attribute: { className: 'input-wrap'},
  children: [
   {
     tagName: 'input',
     attribute: {
       type: "text",
       autocomplete:"off",
       value:"",
       id:"mq",
       class:"input",
       title:"Please enter search words."
      }
  },
  {
   tagName: "button",
   attribute: null,
   children: 'search'}}]Copy the code

When you write this HTML code directly in React, it’s actually created using the React.createElement() method, creating something like this

{
  type: 'div',
  props: {className: 'input-wrap' },
  children: [
   {
     type: 'input',
     props: { 
         type:'text', 
         autocomplete:"off", 
         value:"",id:"mq", 
         class:"input", 
         title:"Please enter search words."
     },
     {
        type: 'button',
        props: null,
        children: 'search'}}]Copy the code

You can think of native javascript document.createElement() and JQ $(“”) to create a JS object and a JQ object. React is an instantiation object

React is not the same as the first two, but I think there are similarities. For example, the createElement method under React is still the same as the method under the native Document document object

If native javascript is solid, it’s not hard to see React doing a layer of transformation here

Since the UI(DOM) information described by JS objects is the same as the structural information displayed by HTML, why not use JS objects instead, because the way to write with object literals is too tedious, smelly and long, and the structure is not clear, if you use HTML to display UI information, then much simpler

React. Js extends the javascript syntax to allow javascript to write HTML tags directly in JAVASCRIPT code, making it much easier to write. The compilation process converts htML-like JSX structures into JavaScript object structures

The code above:

import React from 'react'
import ReactDOM from 'react-dom'

class Search extends React.Component {
render () {
  return (
   <div class="input-wrap">
     <input 
        type="text" 
        autocomplete="off" 
        value="" 
        id="mq" 
        class="input" 
        title="Please enter search words."/> <button> </div>)}} reactdom.render (<Search />, document.getelementbyid ('root'))Copy the code

When compiled by Babel, JSX is translated into a function call called react.createElement (), as shown below

import React from 'react'
import ReactDOM from 'react-dom'

class Search extends React.Component {
   render () {
     return (
       React.createElement(
        "div",
        {className: 'input-wrap'},
       React.createElement(
         "input",
         { type:'text',
           autocomplete:"off",
           value:"",
           id:"mq",
           class:"input",
           title:"Please enter search words." 
         }
     ),
     React.createElement(
       'button',
       null,
       "Search"
      )

    )
  )
 }
}

ReactDOM.render(
React.createElement(Search, null),
document.getElementById('root'));Copy the code

In other words, if you customize a component: for example, the green button

import React from 'react';
import ReactDOM from 'react-dom'

class ElButton extends React.Component {
        constructor(props){
                super(props);
             
         }
          render() {
               return (
                      <button style={ {background: this.props.bgColor}  }>{ this.props.children }</button>
               )
        }
}

ReactDOM.render(<ElButton bgColor="green"</ElButton>, document.getelementById ('root'));
Copy the code

After Babel’s transformation

React.createElement(
    ElButton,
    { bgColor: green},
    children: "Green button"
)
Copy the code

After compilation, the JSX expression is turned into a normal JavaScript function call and evaluated to get a JavaScript object

React. CreateELmenet builds a javascript object to describe your HTML structure, including tag names, attributes, child elements, and event objects. Use React. Function substitution)

The react-DOM is introduced to convert the virtual DOM to the real DOM and insert the DOM element into the page, which is the Re Actdom.render () does something that renders the component and constructs a DOM tree, which is then inserted into a specific element on the page

So when you write a component, you start with two files

When using JSX to finally render the page structure to the browser: it goes through the following process: If you make assertions in the code, the process is very clear

JSX is essentially a javascript object that describes UI structure information

Compared to writing JS, writing HTML is easier, but it is not simple oh, because writing JS is more brain-burning, easy to lose hair ah

However, the level of RMB in hand depends more on your JS level… , this is indeed drop,JS level is high, can directly shout high price

summary

  • JSX is a syntactic extension of the JavaScript language that looks like but isn’t HTML, with additional capabilities that native HTML tags don’t have, such as custom attributes and subsequent component values

  • What does the UI look like depending on the JSX object structure, in other words, the JSX content structure returned after the return keyword in the render() function

  • The react. js library was introduced to parse and recognize JSX syntax and create the virtual DOM, while the React-DOM was introduced to render components, mount components to specific locations, and convert the virtual DOM into the real DOM and insert it into the page

conclusion

This article focuses on what is JSX? React uses JSX syntax to convert the JSX syntax into a real DOM and renders it into a page. There are also a few things to note about JSX I’ll continue next time