What is JSX?

It is neither a string nor HTML. It is a syntax tag similar to XML, which cannot be run directly in a browser. It is compiled into Js standard executable syntax through various compilers.

JSX usage rules

  • Code blocks (beginning with {) are parsed using JavaScript rules.
  • Tags (beginning with <) are parsed using HTML rules;
  • Define attribute names with little camel humps
  • Custom attribute data-[attribute name]

How does JSX compile

parsing

JSX is not standard Javascript code it requires the babel-preth-react-app syntax parsing package to parse into Javascript recognized code that escapes the JSX syntax tag into the react.createElement () method call.

const element = (
    <div className="my-class" >JSX syntax tag</div>
);
Copy the code

Babel:

const element = React.createElement(
    'div'./ / the type label
    {className:'my-class'}, / / props attribute
    'JSX syntax tag ' / / the children
);
Copy the code

Generating the virtual DOM

React. CreateElement will be converted to a virtual DOM, that is, an object.

   constjsxObj = {type: 'div'.// Store the label name or component name
       props: {// props: properties object (if there is a child element, a children attribute is passed in, if there is no child element, there is no children attribute)
        style: ' '.className: 'my-class'.children: 'JSX syntax tag ' // It may be an array, it may be a string or it may be an object.},key: null.ref: null
    }
Copy the code

Generating a real DOM

Principle is to render JSX generated objects generated ‘type’ type of DOM elements, the attributes’ props’ traversal appended to the DOM, for example, the name of the class the className, style, children… And then mount it to the specified container.

Here is a custom render function:

function render(jsxObj, container,callback){
    let {type,props} = jsxObj;
    // Create a DOM
    let element = document.createElement(type);
    for(let key in props){
        _props = props[key];
        if(element.hasOwnProperty(key))break;
        if(typeof _props=='undefined')break;
        // Event listener
        if(key.startsWith('on')) {let attch= key.slice(2).toLowerCase();
            element.addEventListener(attch, _props, false);
            continue;
        }
        key = key.toUpperCase();

        switch (key){
             case 'CHILDREN':
                // Determine if there is a child DOM
                if (typeof _props === "string"){
                    element.innerText = _props
                }else {
                  / / recursion
                    for(let children in _props){
                        render(children,element)
                    }
                }
                break;
             case 'STYLE':
                
                let _style =  Object.keys(_props).map((name) = >{
                    let value = _props[name];
                    return `${name}:${value}`;
                }).join('; ');
                element.setAttribute('style', _style)
                break;
             case 'CLASSNAME':
                element.setAttribute('class', _props)
                break;
             default:
                // Other attributes
                break;
        }
    }   
    
   container.appendChild(element);
   callback&&callback();
}
Copy the code

Matters needing attention

  • Attribute names are small hump names
  • There can only be one top-level tag (element) in JSX syntax
  • When using components, the first letter must be capitalized
  • JSX expressions cannot use if else (ternary operators can be used)
  • The method called will point to undefined, which is exactly what this points to

It’s not a React bug, it’s native to JavaScript. If you pass a function name to a variable and then call the method by enclosing parentheses () after the variable,

    const obj = {
        title: 'JSX'.func:function(){
            console.log(this)
        }       
    }
    obj.func(); // this points to obj

    let funcb = obj.func
    funcb(); // This points to window
Copy the code

JSX advantages

  • JSX performs faster
  • More secure against injection attacks, error detection at compile time
  • Easy for developers to read, write templates more simple and fast