Getting started with JSX

JSX is a technology introduced by React. Let's delve into

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:

  • classbecomeclassName
  • forbecomehtmlFor

Because they are reserved words in JavaScript.

This is a JSX code snippet that wraps two components into onedivlabel:

  <BlogPostsList />
  <Sidebar />

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

  React.createElement('div', { id: 'test' },
    React.createElement('h1', null, 'A title'),
    React.createElement('p', null, 'A paragraph')


  <div id="test">
    <h1>A title</h1>
    <p>A paragraph</p>

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-appYou need to set up Babel yourself.


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'
  <div id="test">
    <h1>A title</h1>

This is a basic example. Braces acceptedanyJS code:

const paragraph = 'A paragraph'
    {, i) => {
      return <tr>{row.text}</tr>

as you can seeWe nest JavaScript in JSX and nest it in JSX. You can conduct in-depth research as needed.


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


Since JSX is JavaScript,classIs a reserved word, you cannot write

<p class="description">

But you need to use

<p className="description">

Also applies toforIs translated intohtmlFor.

Style attributes change their semantics

ThisstyleAttributes 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 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 propertiesstyleThe 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)


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.

  1. Write a media query
  2. Style animation
  3. Reference pseudo-classes (e.g.:hover)
  4. 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.


ThisvalueThe attribute always holds the current value of the field.

ThisdefaultValueThe attribute contains the default value that was set when the field was created.

This helps to solve some regular weird behaviorsDOMInteraction during inspectioninput.valuewithinput.getAttribute('value')Return a current value and an original default value.

This also applies totextareaDomain, for example

<textarea>Some text</textarea>

But instead

<textarea defaultValue={'Some text'} />

in order toselectField instead of using

  <option value="x" selected>


<select defaultValue="x">
  <option value="x">...</option>

More consistent onChange

Pass the function toonChangeProperties, you can subscribe to events on form fields.

Even in all areas, it can work consistentlyradio,selectwithcheckboxInput field triggeronChangeevent.

onChangeIt also triggers when entering charactersinputortextareasite.

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>{'&copy; 2020'}</p>

But this is not, it is a printed matter&copy; 2020Because the string has been escaped.

To solve this problem, you can move the entity outside the expression:

<p>&copy; 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>


<p>Something becomes this</p>

Eliminates vertical whitespace




To solve this problem, you need to add spaces explicitly by adding a space expression like the following:

  {' '}becomes
  {' '}this

Or by embedding the string in a space expression:

  {' becomes '}

Add comments in JSX

You can add comments to JSX using normal JavaScript comments in expressions:

  {/* a comment */}
    //another comment

Propagation properties

In JSX, a common operation is to assign values to attributes.

Instead of doing it manually, for example

  <BlogPost title={data.title} date={} />

You can pass

  <BlogPost {} />

as well asdataWith 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 embeditemsArrange 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:mapInstead of a for-of loop:

const elements = ['one', 'two', 'three'];
return (
    {, index) => {
      return <li key={index}>{value}</li>

Download mine for freeResponse Handbook

More response tutorials: