JSX syntax details

In the react basics article, we used the react.createElement() method to create a single layer element. This method works fine, but it can be a bit tedious and unintuitive when nested

1. What is JSX

JSX stands for JavaScript XML. An XML-like syntax for building tags inside the React component. JSX developed a set of syntactic candy for react.js, which is the basis for the use of react.js. React works without JSX, however it is recommended to use JSX because it improves the readability of components. Github. IO/JSX /

2. Basic use of JSX

2.1 Why use JSX

Cause 1: Using React. CreateElement () to create an element is cumbersome

Reason two: The code is not concise, can not see the structure of the hierarchy

Such as:

React.createElement(  'div'.null,  
    React.createElement('h1'.null.'Shopping list'), 
    React.createElement('ul'.null, 
       React.createElement('li'.null.'huawei'),  
       React.createElement('li'.null.'iPhone')))Copy the code

2.2 JSX profile

  • JSX is short for JavaScript XML, which stands for code written in XML (HTML) format within JavaScript code
  • Advantages: Declarative syntax is more intuitive and has the same structure as HTML, reducing learning costs and improving development efficiency
  • JSX is at the heart of React

Create the element using the react.createElement () method

React.createElement(  'div'.null,  
    React.createElement('h1'.null.'Shopping list'), 
    React.createElement('ul'.null, React.createElement('li'.null.'huawei'),  React.createElement('li'.null.'iPhone')))Copy the code

And you can see that this is not intuitive

JSX grammar

<div>
   <h1>The shopping list</h1>
   <ul>
      <li>huawei</li>
      <li>iPhone</li>
   </ul>
</div>
Copy the code

Using JSX syntax, structure is clear, is usually written HTML tags

2.3 Procedure

  1. Create react elements using JSX syntax

    / / JSX syntax
    constEl = (<h1>Hello JSX! < / h1 >)Copy the code
  2. Use the reactdom.render () method to render the React element into the page

    / / rendering
    ReactDOM.render(el, document.querySelector('#root'))
    Copy the code

2.4 pay attention to the point

  1. The react element’s attribute names use the hump nomenclature tabIndex –> tabIndex
  2. Special attribute names: class –> className, for –> htmlFor
  3. In React, all labels must be closed, whether single or double
  4. Recommendation: Wrap JSX structures in parentheses to avoid the auto-insert semicolon trap in JS

3. Use JavaScript expressions in JSX

thinking

  • JSX syntax is fine, but it’s no different than writing static HTML tags
  • How to display data dynamically? Real-world applications typically fetch data from a server and display it on a page
  • As a guess, since JSX is written directly in JS, variables or functions in JS should be accessible in JSX
const data = 'OPPO'
render() {
    return (
        <div>
           <h1>The shopping list</h1>
           <ul>
              <li>huawei</li>
              <li>iPhone</li>
              <li>{data}</li>
          </ul>
       </div>)}Copy the code

3.1 Embedding JS expressions

  • Syntax: {JavaScript expressions}

    const name = 'Ming'
    const dv = (
       <div>Hello, my name is {name}</div>
    )
    Copy the code

    Pay attention to the point

    • Single parentheses can contain any JavaScript expression, such as ternary expressions, addition, subtraction, multiplication, and division, arrays, and strings
    • Statements cannot appear in single braces (e.g., if/for, etc.)
    • JS objects generally only appear in the style property

4. JSX conditional rendering

thinking

  • Conditional rendering: Render different JSX structures according to different conditions
  • Typical scenario: Loading effects in Ajax asynchronous request data
  • So given what we know, how do we do that
  • Although you cannot write if/else judgments directly in JSX, you can embed function expressions
  • Make if/else judgments in function expressions

4.1 Conditional rendering implementation

  • This can be done using if/else or ternary operators in function expressions

    const loadData = () = > {
        if(idLoading) {
            return <div>Data loading...</div>
        } else {
            return <div>Data loading completed</div>}}const load = (
        <div>
            {loadData()}
        </div>
    )
    Copy the code

5. JSX list rendering

thinking

  • The data structure that the front end gets in actual development

    const books = [
        {id: 1.name: 'React'},
        {id: 2.name: 'Vue'},]Copy the code
  • How does this translate into the following structure

    const books = [
        <li>React</li>.<li>Vue</li>,]Copy the code

5.1 List rendering implementation

  • By iterating through the array of methods map

  • Array.prototype.map()

    const list = (
        <ul>
            {books.map(item => <li>{item.name}</li>)}
        </ul>
    )
    Copy the code

6. JSX style processing

  1. Inline style – style

    <h1 style={{ color: 'red', backgroundColor: 'skyblue' }}>JSX style handling</h1>
    Copy the code
  2. The name of the class – the className

    You need to import the style file using import ‘style file path/style file name.css’, and the title class is defined in the xxx.css file

    <h1 className="title">JSX style handling</h1>
    Copy the code

conclusion

  • JSX is at the heart of React
  • JSX stands for writing HTML structures in JS code. It is the embodiment of React declarative style
  • Arbitrary UI structures can be described using JSX with embedded JS expressions, conditional rendering, and list rendering
  • It is recommended to style JSX using a className