BASIC USE OF JSX

No.1 INTRODUCTION TO JSX

Through the +1 small application of the previous blog, we can appreciate that compared with Vue, writing such a small application with React is more troublesome and the code is more chaotic. Developers who have been exposed to Vue should know that Vue has two builds, and if you use the non-full version alone, it will not be much of an advantage compared to the above small applications that implement +1 with React, which means that there is one more convenience for automatic view refresh.

But the non-full version of Vue works with the vue-loader, which allows developers to write <template><script >< style > in .vue files, these will eventually be turned into a construction option or component by the vue-loader, which can meet the user’s small size and improve the efficiency of the developer. So what are react-like loaders or plugins to improve the developer experience? — That’s JSX.

JSX is an extension of JavaScript. Official explanation: “Actually, JSX is just the syntactic sugar of the function”. It’s all about making up for the relative clutter of React code.React.createElement(component, props, …children)

React provides JSX to improve the developer experience, and similar to Vue, developers only need to write html code in .js file, and the rest is left to jsx-loader, which compiles the relatively clear code written by these developers into React.createElement(…). The code of the form. React used jsx-loader for escaping in the early years, but in recent years it has been replaced by babel-loader, which was built into webpack, so React developers don’t need to install anything. So how to use this thing?

No.2 How to introduce babel

Babel was introduced through BootCND

After the introduction of babel.min.js, you need to change the <script > to <script type= “text/babel'” > every time you write JavaScript, babel will automatically translate the babel type code (can be understood as translation), let’s re-implement the +1 small application in combination with babel.

<div id="root"></div>
<script src="https://cdn.bootcss.com/react/16.10.2/umd/react.development.js"></script>
<script src="https://cdn.bootcss.com/react-dom/16.10.2/umd/react-dom.development.js"></script>
<script src="https://cdn.bootcss.com/babel-standalone/7.0.0-beta.3/babel.min.js"></script>
<script type="text/babel"> // Babel-loader will translate this babel code, parse it into js and insert script to replace the babel tag
    let num = 0;
    const App = () => ( // App must be a function, otherwise manually refreshing the view will cause problems
        <div className="red"> // No React.createElement('div', {className: 'red'}, [n, React.createElement()])
            {n} // Variables can be wrapped with {}
            <button
                onClick={() => {
                    num += 1;
                    render(); // After the variable is changed, the view needs to be refreshed manually
                }}
            >
            +1
            </button>
        </div>
    );
    const render = () => ReactDOM.render(<App />, document.querySelector("#root"));
    render(); // Here <App /> is similar to App(), it can now be called in the form of a component
</script>

Combined with the babel-loader, the code has been introduced a lot, all the tags can be written in html tags, if you need to insert js variables or functions, wrap them in {} , compared to the previous way to create a note, you need to use React.createElement(). It seems to be much simpler than Vue now, because everything is original in JavaScript, and Vue needs the data attribute to implement variables, and the v-on directive to implement the click function.

But this way of bootCDN is not very recommended, and that’s advice. Never use this BootCDN approach in production again, because it’s too inefficient, and it’s going to download a babel.min .js on the user’s machine, and it’s also going to translate JSX to JS on the browser side, so why not do it at build?

Use the create-react-app approach

This React’s create-react-app command line and Vue’s VueCLI are of the same nature, and the way to install and create projects is as follows:

yarn global add create-react-app    // Or npm, because the content is relatively large, it is recommended to use yarn
 
create-react-app ProjectName    // Similar to Vue's vue create ProjectName
//After the creation is complete, you can run the yarn start command in the project directory, and you can see the React webpage to indicate that the project was created successfully
<div id="root"></div>    // index.html
//App.js
import React from 'react'
const App = () => {    // Although it is a js file, it can write babel code
    return (
        <div>App组件</div>  // In fact, React.createElement() is still called in the babel syntax, so React needs to be introduced
    )
}
export default App
 
// index.js file
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App.js'
 
ReactDOM.render(<App />, document.getElementById('root')); // yarn start can see the hi page

We can notice that the code written in the App .js file does babel, because webpack lets JS take babel-loader by default.

  • The className property. During the process of creating a component, if a tag has a class attribute, you need to write the className=”red” code, because the jsx syntax we wrote eventually needs to bebel-loader to be escaped into js, and the code in js is created by React.createElement(‘div’, {className:’red’}, [n]).
  • Insert a variable. All JS code in the tag is wrapped in { }, if you need the variable n, then use { } to wrap n, if you need an object, then wrap the object with { }, such as {name:’erha’} }. {
  • during component creation, when return is required internally, be sure to add () after return.

No.3 Now compare it with Vue

The non-full version of Vue has the help of v-loader, which can escape html into the render function, while React has the help of babel-loader, and can also write html tags in js files, which now seems to be comparable in the ease of development. For example, we can analyze it with an if-else example:

//Vue
<template>
    <div>
        <div v-if="n%2===0">n is even</div>
        <span v-else>n is odd</span>
    </div>
</template>
 
//React
const Component = () => {
    return (    // Don't miss the parentheses
        <div>
            { n%2===0 ? <div>n is even</div> : <span>n is odd</span> } //js syntax is wrapped with {}
        </div>
    )
}
 
//React
const Component = () => {
    const inner = n%2===0 ? <div>n is even</div> : <span>n is odd</span>
    return (
        <div>
            { inner }    // It can be seen that React is more flexible, as long as it is js code, you can write whatever you want
        </div>
    )
}

Conclusion: Vue: Conditional judgments can only be written using the v-if/v-else syntax provided by Vue, but the rules will be very clear. React: As long as it’s JavaScript code, you can write it as you want, which is very flexible, but the regulations may not be as clear as Vue. Another example is the comparison of the way circular statements are written in two frameworks:

// Iterating over arrays and objects in Vue
<template>
    <div>
        <div v-for="(n, index) in numbers" :key="index">
            Subscript {{index}}, value is {{n}}
        </div>
    </div>
</template>
 
//React
const Component = (props) => {
    return (
        <div>
            { props.numbers.map((n,index) => {return <div> subscript {index} value is {n} )}
        </div>
    )
</div>)

Leave a Reply