JSX is a technology introduced by React. Let's delve into
- Introduction to JSX
- Getting started with JSX
- Translate JSX
- JS in JSX
- HTML in JSX
- CSS in React
- Forms in JSX
- JSX auto-escaping
- White space in JSX
- Add comments in JSX
- Propagation properties
- How to loop in JSX
Introduction to JSX
JSX is a technology introduced by React.
Although React does not need to use JSX to work properly, it is an ideal technology for handling components, so React benefits a lot from JSX.
Initially, you might think that using JSX is like combining HTML andJavaScript(And the CSS you will see).
But this is incorrect, because when using JSX syntax, you are actually writing declarative syntax about what the component UI should be.
And the UI you are describing is not using strings, but using JavaScript, which allows you to do a lot of things.
Getting started with JSX
This is how to define an h1 tag that contains a string:
const element = <h1>Hello, world!</h1>
It looks like a strange combination of JavaScript and HTML, but in fact, they are all JavaScript.
What looks like HTML is actually syntactic sugar for defining components and their positions within the markup.
In JSX expressions, you can easily insert attributes:
const myId = 'test'
const element = <h1 id={myId}>Hello, world!</h1>
You only need to put a dash in the attribute (-
), but convert it to camelCase syntax, and the following 2 special cases:
class
becomeclassName
for
becomehtmlFor
Because they are reserved words in JavaScript.
This is a JSX code snippet that wraps two components into onediv
label:
<div>
<BlogPostsList />
<Sidebar />
</div>
Always need to close tags, because XML is more than HTML (if you remember the days of XHTML, this will be familiar, but since then, HTML5's loose syntax has won). In this case, use the automatic closing tag.
Please note how I packed 2 components into onediv
. why? becauseThe render() function can only return one node, So if you want to return to 2 siblings, just add a parent. It can be any label, not justdiv
.
Translate JSX
The browser cannot execute JavaScript files containing JSX code. They must first be converted to regular JS.
how is it? By executing a calledDump.
We have already said that JSX is optional, because for each JSX line, you can use the corresponding ordinary JavaScript alternatives, and this is what JSX is ported to.
For example, the following two constructions are equivalent:
Plain JS
ReactDOM.render(
React.createElement('div', { id: 'test' },
React.createElement('h1', null, 'A title'),
React.createElement('p', null, 'A paragraph')
),
document.getElementById('myapp')
)
JSX
ReactDOM.render(
<div id="test">
<h1>A title</h1>
<p>A paragraph</p>
</div>,
document.getElementById('myapp')
)
This very basic example is just a starting point, but as you can already see, normal JS syntax is much more complicated than using JSX.
At the time of writing, the most popular way istransplantIs to useTower of Babel, Which is the default option at runtimecreate-react-app
, So if you use it, don’t worry, everything will happen behind your scenes.
If you don't usecreate-react-app
You need to set up Babel yourself.
JS in JSX
JSX accepts any kind of JavaScript mix.
Whenever you need to add some JS, just put it in curly braces{}
. For example, here is how to use constant values defined elsewhere:
const paragraph = 'A paragraph'
ReactDOM.render(
<div id="test">
<h1>A title</h1>
<p>{paragraph}</p>
</div>,
document.getElementById('myapp')
)
This is a basic example. Braces acceptedanyJS code:
const paragraph = 'A paragraph'
ReactDOM.render(
<table>
{rows.map((row, i) => {
return <tr>{row.text}</tr>
})}
</table>,
document.getElementById('myapp')
)
as you can seeWe nest JavaScript in JSX and nest it in JSX. You can conduct in-depth research as needed.
HTML in JSX
JSX is very similar to HTML, but is actually XML syntax.
Finally, you render HTML, so you need to understand some differences between how to define certain content in HTML and how to define them in JSX.
You need to close all tabs
Just like in XHTML, if you have used it before, you need to close all tags: no more<br>
Instead, use the auto-closing label:<br />
(The same is true for other tags)
camelCase is the new standard
In HTML, you will find that there are no capitalization attributes (for example,onchange
). In JSX, they are renamed to their equivalent camelCase:
onchange
=>onChange
onclick
=>onClick
onsubmit
=>onSubmit
class
becomeclassName
Since JSX is JavaScript,class
Is a reserved word, you cannot write
<p class="description">
But you need to use
<p className="description">
Also applies tofor
Is translated intohtmlFor
.
Style attributes change their semantics
Thisstyle
Attributes in HTML allow you to specify inline styles. In JSX, it no longer accepts strings, but inCSS in ReactYou will understand why this is a very convenient change.
form
Form field definitions and events have been changed in JSX to provide more consistency and practicality.
Forms in JSXIntroduce the table in detail.
CSS in React
JSX provides a good way to define CSS.
If you have a little experience with HTML inline styling, at first glance you will find that you are 10 or 15 years behind, entering the world where inline CSS is completely normal (now demonized, usually just a "quick fix"). Program).
JSX styles are not the same thing: first, JSX does not accept strings containing CSS propertiesstyle
The property only accepts one object. This means that you define properties in the object:
var divStyle = {
color: 'white'
}
ReactDOM.render(<div style={divStyle}>Hello World!</div>, mountNode)
or
ReactDOM.render(<div style={{ color: 'white' }}>Hello World!</div>, mountNode)
The CSS values you write in JSX are slightly different from normal CSS:
- The key attribute name is camelCased
- Value is just a string
- You separate each tuple with a comma
Why is this the first choice compared to ordinary CSS/SASS/LESS?
CSS is aUnresolved issues. Since its establishment, dozens of tools surrounding it have risen and then fallen. The main problem with CSS is that it has no scope and it is easy to write CSS that is not enforced in any way, so "quick fixes" will affect elements that should not be touched.
JSX allows components (defined in React, for example) to completely encapsulate their styles.
Is this the preferred solution?
Unless needed, inline styles in JSX would be nice.
- Write a media query
- Style animation
- Reference pseudo-classes (e.g.
:hover
) - Reference pseudo-element (e.g.
::first-letter
)
In short, they cover the basics, but this is not the ultimate solution.
Forms in JSX
JSX has made some changes to the way HTML forms work, in order to make it easier for developers.
value
withdefaultValue
Thisvalue
The attribute always holds the current value of the field.
ThisdefaultValue
The attribute contains the default value that was set when the field was created.
This helps to solve some regular weird behaviorsDOMInteraction during inspectioninput.value
withinput.getAttribute('value')
Return a current value and an original default value.
This also applies totextarea
Domain, for example
<textarea>Some text</textarea>
But instead
<textarea defaultValue={'Some text'} />
in order toselect
Field instead of using
<select>
<option value="x" selected>
...
</option>
</select>
use
<select defaultValue="x">
<option value="x">...</option>
</select>
More consistent onChange
Pass the function toonChange
Properties, you can subscribe to events on form fields.
Even in all areas, it can work consistentlyradio
,select
withcheckbox
Input field triggeronChange
event.
onChange
It also triggers when entering charactersinput
ortextarea
site.
JSX auto-escaping
In order to reduce the risk of XSS vulnerabilities, JSX enforces automatic escaping of expressions.
This means that you may encounter problems when using HTML entities in string expressions.
You want the following to be printed© 2020
:
<p>{'© 2020'}</p>
But this is not, it is a printed matter© 2020
Because the string has been escaped.
To solve this problem, you can move the entity outside the expression:
<p>© 2020</p>
Or use a constant to print the Unicode representation corresponding to the HTML entity you need to print:
<p>{'\u00A9 2020'}</p>
White space in JSX
To add spaces in JSX, there are 2 rules:
Horizontal white space is trimmed to 1
If there are spaces between elements in the same line, all spaces will be trimmed to 1 space.
<p>Something becomes this</p>
become
<p>Something becomes this</p>
Eliminates vertical whitespace
<p>
Something
becomes
this
</p>
become
<p>Somethingbecomesthis</p>
To solve this problem, you need to add spaces explicitly by adding a space expression like the following:
<p>
Something
{' '}becomes
{' '}this
</p>
Or by embedding the string in a space expression:
<p>
Something
{' becomes '}
this
</p>
Add comments in JSX
You can add comments to JSX using normal JavaScript comments in expressions:
<p>
{/* a comment */}
{
//another comment
}
</p>
Propagation properties
In JSX, a common operation is to assign values to attributes.
Instead of doing it manually, for example
<div>
<BlogPost title={data.title} date={data.date} />
</div>
You can pass
<div>
<BlogPost {...data} />
</div>
as well asdata
With ES6, the object will automatically be used as an attributeSpread operator.
How to loop in JSX
If you need to loop to generate a set of JSX local elements, you can create a loop and then add JSX to the array:
const elements = [] //..some array
const items = []
for (const [index, value] of elements.entries()) {
items.push(<Element key={index} />)
}
Now when rendering JSX, you can embeditems
Arrange the array by wrapping it in curly braces:
const elements = ['one', 'two', 'three'];
const items = []
for (const [index, value] of elements.entries()) {
items.push(<li key={index}>{value}</li>)
}
return (
<div>
{items}
</div>
)
You can perform the following operations directly in JSX:map
Instead of a for-of loop:
const elements = ['one', 'two', 'three'];
return (
<ul>
{elements.map((value, index) => {
return <li key={index}>{value}</li>
})}
</ul>
)
Download mine for freeResponse Handbook
More response tutorials:
- A simple React application example: Get GitHub user information through API
- Build a simple counter with React
- VS Code setup for React development
- How to pass props to child components through React Router
- Create an application using Electron and React
- Tutorial: Create a spreadsheet with React
- Roadmap for learning React
- Learn how to use Redux
- Getting started with JSX
- Stylized components
- Introduction to Redux Saga
- Introduction to React Router
- Introduction to React
- Reaction component
- Virtual DOM
- Reaction event
- Reaction state
- Reaction props
- Reaction fragment
- React Context API
- Reaction PropTypes
- Reaction Concept: Declarative
- React: How to display other components when clicked
- How to loop inside React JSX
- Props and status in React
- Should you use jQuery or React?
- How much JavaScript do I need to know to use React?
- Gatsby Introduction
- How to reference DOM elements in React
- One-way data flow in React
- React high-end components
- React to life cycle events
- Reaction concept: immutability
- Reaction concept: purity
- Introduction to React hooks
- Introduction to create-react-app
- Reaction concept: composition
- React: demo component and container component
- Code splitting in React
- Server-side rendering with React
- How to install React
- CSS in React
- Use SASS in React
- Processing forms in React
- Reaction strict mode
- Reaction portal
- React rendering props
- Test React components
- How to pass parameters to event handlers in React
- How to deal with errors in React
- How to return multiple elements in JSX
- Conditional rendering in React
- Reaction, how to transfer props to subcomponents
- How to get the value of an input element in React
- How to use useState React hook
- How to use useCallback React hook
- How to use useEffect React hook
- How to use useMemo React hook
- How to use useRef React hook
- How to use useContext React hook
- How to use useReducer React hook
- How to connect your React app to the backend of the same source
- Reaching the router tutorial
- How to use React Developer Tools
- How to learn React
- How to debug a React application
- How to render HTML in React
- How to fix `dangerouslySetInnerHTML` does not match the error in React
- How can I solve the problem of React login form status and browser auto-fill
- How to configure HTTPS in React application on localhost
- How to fix the "Component cannot be updated while rendering other components" error in React
- Can I use React hooks within the conditions?
- Using useState with objects: how to update
- How to move in code blocks using React and Tailwind
- React, focus on an item in React when added to the DOM
- Response, edit text on doubleclick