In the past six months, VUE has been basically used to develop projects, and we have some experience. In the future, we will launch a complete VUE based management system at the front and rear ends. Start learning React today, starting with the JSX that defines the React component. What is JSX? What does it have to do with JavaScript? This article will study together.
What exactly is JSX?
JSX, that is, JavaScript, XML, the syntax extension of JavaScript, allows HTML to be written in JavaScript files (this is the reason for personal resistance). Instead of creating, modifying or splicing HTML through JavaScript objects, you can use XML like syntax to create elements and generate corresponding DOM elements at compile run time.
How does it look? See the following code:
const jsx = <div>Hello React</div>;
How to use JSX?
So how to use JSX in practice? JSX is flexible. No matter which programming method, it needs to follow certain rules. Let's introduce them one by one.
Using expressions in JSX
Suppose you want to use JavaScript variables in the HTML template. Using curly braces {}, you can interpolate variables to obtain dynamic values:
const title = "DevPoint"; const expression = <h1>Hello {title}</h1>;
Here {title} will be replaced with DevPoint in the h1 element. Of course, you can not only embed JavaScript variables, but also use more complex expressions:
const a = 1; const b = 1; const expression = ( <code> {a} + {b} = {a + b} </code> );
This will output 1 + 1 = 2, and expressions are often used to generate a list of HTML elements when dealing with arrays. Suppose there is a dynamic menu that receives data from the API:
{ "menu": [ { "name": "Home", "link": "/" }, { "name": "About", "link": "/about" }, { "name": "Contact", "link": "/contact" } ] }
You can then map the entire array using a JSX expression:
const menu = <ul>{menu.map((item) => console.log(item))}</ul>;
Here, each element is recorded to the console using the Array.map method in the JSX expression, but how to display the list elements?
const menu = ( <ul> {menu.map((item) => ( <li> <a href={item.link}>{item.name}</a> </li> ))} </ul> );
You can simply return the required elements from the function, which is equivalent to explicitly writing out the return keyword below:
const menu = ( <ul> {menu.map((item) => { return ( <li> <a href={item.link}>{item.name}</a> </li> ); })} </ul> );
Expressions can also be used to create conditional statements or use ternary operators to return different HTML elements according to the value of variables, as follows:
{ name && <h1>Hello {name}</h1>; } { /* Here are the notes */} { name ? <h1>Hello {name}</h1> : null; }
As you can see, annotations in JSX are also used in expressions. If you want to write / / before a line, it will also be printed to the final HTML file because it is interpreted as free stream text. Therefore, you need to use expressions when using annotations.
Using attributes in JSX
As you can see above, you can also use HTML attributes in JSX elements as usual. You can also use JSX expressions for attributes, or if you are using static values, you can define them using quotation marks in regular HTML:
<a href={item.link} target="_blank"> {item.name} </a>;
In JSX, these are called props. It should be noted that when it comes to attributes using dashes, JSX uses hump case. For example, if you want to add the aria attribute, do the following:
<div aria-label="Label"></div> <div aria-checked="true"></div> <div tab-index="0"></div> <div ariaLabel="Label"></div> <div ariaChecked="true"></div> <div tabIndex="0"></div>
There is a special exception when using attributes in JSX, that is, using HTML classes. Since the word class is a reserved keyword in JavaScript, you need to use className instead:
<div class="carousel"></div> <div className="carousel"></div>
Always turn off JSX Tags
When using the auto close tag or using elements that are purely used to convey visual information, and these elements do not have any child elements, ensure that the tag is always closed, otherwise an error will occur:
{/* Wrong way */} <br> <img> <div> {/* The right way */} <br /> <img /> <div className="loader" />
Return to JSX
Another important rule to note is that only one JSX element can be returned at a time. Look at the following HTML elements:
<span className="tooltip">...</span> <div className="tooltip-backdrop" />
This example is invalid because it attempts to return multiple adjacent JSX elements. In order to repair it, it needs to be wrapped in the parent:
<span className="tooltip-container"> <span className="tooltip">...</span> <div className="tooltip-backdrop" /> </span>
Alternatively, if you don't want to pollute the DOM tree with unnecessary HTML elements, you can also use a special tag called fragment:
<React.Fragment> <span className="tooltip">...</span> <div className="tooltip-backdrop" /> </React.Fragment> {/* perhaps */} <Fragment> <span className="tooltip">...</span> <div className="tooltip-backdrop" /> </Fragment> {/* perhaps */} <> <span className="tooltip">...</span> <div className="tooltip-backdrop" /> </>
The above three examples will generate the same code, all work properly, and no additional DOM elements will be added to the HTML file.
Store JSX
JSX elements can also be stored in variables and passed to other JSX elements for use. However, it is likely to involve storing JSX elements in functions:
const Slider = () => ( <div>This is a component</div> ); <Slider />
In addition, it is recommended to capitalize the function, otherwise it will be treated as an HTML element. The exception is to use object methods, such as:
const component = { slider() { return <div>This is a component</div> } }; <component.slider />
By using functions, you can also pass plug-ins that can be used for HTML elements:
const Slider = ({ size }) => ( <div className={size}>This is a component that can control the size</div> ); <Slider size="large" /> <Slider size="medium" /> <Slider size="small" />
As you can see above, you can use not only the names of HTML attributes, but also custom names.
What does JSX generate?
So what exactly does JSX generate? The browser cannot understand JSX syntax, so React needs to compile it into JavaScript function calls that the browser can understand. These JavaScript function calls will eventually create and update the necessary HTML elements. Taking the following code fragment as an example, it will generate the following function calls:
const jsx = <div>Welcome to React</div>; React.createElement("div", null, "Welcome to React"); const jsx = <div className="carousel" />; React.createElement("div", { className: "carousel" });
If the JSX element has child elements, these child elements will also be compiled into the React.createElement call and finally generated in the JavaScript package, as follows:
React.createElement(component, props, ...children);
Similarly, if you use lowercase for components, they will be treated as HTML elements, so make sure to capitalize them:
<component />; React.createElement("component"); <Component />; React.createElement(Component); <component.slider />; React.createElement(component.slider);
summary
JSX can simplify code, make it easier to use, and make it more readable. To review the important parts of this tutorial, here are some considerations about the connection between JSX and JavaScript:
- JSX is a syntax extension of JavaScript and represents JavaScript XML.
- React can be written with or without JSX, but JSX is strongly recommended.
- JSX supports the use of curly braces to use expressions.
- Attributes in JSX are written using hump nomenclature.
- JSX elements must always be closed. If no child elements are involved, the elements must be closed (paired).
- Only one JSX can be returned at a time. If you need to return multiple elements, use fragments.
- Function can return JSX elements.
- JSX is generated as the React.createElement function call.