Copyright notice: This article is the blogger’s original article, shall not be reproduced without the permission of the blogger.

JSX overview

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

Tags like the one above, which is neither a string nor HTML code, are called JSX, a JavaScript syntax extension, and JSX is a good way to describe how the UI should behave the way it should interact. JSX may be reminiscent of a template language, but it’s not just a template language; it has all the functionality of JavaScript.

Considerations for using JSX:

  • Need to pass throughReactDOM.render()Render.
  • The whole block needs to be tagged with something like a large tag, as in the code snippet below<div> </div>The parcel.
  • Render inside the tag with curly braces {} to evaluate expressions, access variables, and call methods.
  • availablereturnTo return a value.
  • JSX annotation:{/* Comment here */}
    const username = 'xiaohong';
    const firstname = 'zhangsan';
    function checkFriends() {return 'My friend is'+username + 'and'+firstname; } const element = (<div> <h1>hello,{checkFriends()}</h1> {/* This is a line of comment */} {8+5} </div>) reactdom.render (element, document.getElementById('root'));Copy the code

In addition, we can also use the output of arrays.

    const todoList = ['apple'.'banana'.'orange'];
    const element =<div>
        {
            todoList.map(item =>
                <li>{item}</li>
            )
        }
    </div>
    ReactDOM.render(
     element,
     document.getElementById('root'));Copy the code

If the tag has no child elements, that is, no content, use the/to close the tag

const element = <img src={user.avatarUrl} />; 
Copy the code

Babel compiler

As we know, ES(6+) is not perfectly supported by all browsers and has been compiled by various compilers to make JavaScript code compatible with older browsers. We use the Babel online tool to view the compiled JavaScript code as follows:

    var todoList = ['apple'.'banana'.'orange'];
    var element = React.createElement("div", null, todoList.map(function (item) {
      return React.createElement("li", null, item);
    }));
    ReactDOM.render(element, document.getElementById('root'));
Copy the code

Do YOU have to use JSX in React? It wasn’t, but the React team wanted us to, and in fact, the JSX code saved us a lot of trouble.

Does the ES(6+) syntax have to be used when building with JSX? It’s not, but in general, it’s recommended. So those who haven’t mastered ES(6+) grammar should cheer up.