The Science Behind Successful Learning

It used to be that a college education was the doorway to success. At a minimum, a Bachelor’s degree was the key to a good job, if not to a fulfilling career. After years of research, learning…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Describe Elements with JSX

React for Real — by Ludovico Fischer (12 / 48)

👈 Create a Component | TOC | Match Components and Data 👉

JSX is an alternative syntax for React.createElement that doesn’t introduce any new functionality, but makes the code easier to read.

You may be used to describing the user interface in separate template files. React developers came up with an unorthodox solution: a new syntax to describe user interfaces inside JavaScript files. Instead of writing React.createElement by hand, you write the element description in a syntax that’s almost identical to HTML, called JSX. Then, before the application runs, you process your source with a tool called Babel to replace JSX with React.createElement.

When compared to templates, the advantage to this approach is that there are fewer special rules to learn than with a separate template language, and error messages tend to be easier to interpret. The trade-off is that you need a build step to prepare your code for production. To get started fast, right now we’ll use an in-browser Babel transform: it’s too slow for production use and may sometimes lead to odd runtime errors, but it’s enough to practice the syntax.

Let’s convert our Adder component to use JSX instead of React.createElement. Modify your code so it looks like this:

In this version, we return an <h1> element, as if we’d written it in HTML. We then output the value of the sum inside the <h1> element by surrounding the variable name with braces. You can mix the result of any JavaScript expression into the generated markup by enclosing the JavaScript expression in braces.

Once you convert Adder to JSX, the application won’t work anymore because the browser can’t interpret JSX. We’ll use the Babel standalone transformer to translate on the fly JSX into React.createElement calls. Open index.html. Insert a link to Babel’s standalone transpiler right above your own code, and then change your code’s type to text/babel:

Add a comment

Related posts:

Reflecting on Change

2020 and the beginning of 2021 has presented so many challenges and fundamental threats to our understanding of democracy and society as a whole. Last March, as my children were sent home from school…

Pattern 8 Parse Tree

A parse tree is sometimes called a syntax tree (as opposed to an abstract syntax tree). Despite not being that useful for building interpreters and translators, I’m including this pattern because…

MUXIANG Italian Briar Pipe Kit

This Briar Pipe Kit features a classic Italian briar pipe made by the best briar pipe brand MUXIANG. The pipe is made of high-quality briar wood and has a smooth finish. and has excellent…