Our application works, but it’s terribly simple – it only renders a simple string. If we try to add HTML tags to it, they will also be treated as a text string and displayed as text, not as HTML tags.

React uses its own markup language, JSX, which is an extension of the JS language with XML-like syntax. However, it is not XML or HTML, and what’s more, these tags are not interpreted in any way by the browser – they only make it easier for developers to work with React. If you don’t like “placing HTML in JS” there are many alternatives like react-hyperscript or writing your own generated code.

Attention JSX tags are not interpreted by the browser and will lead to errors. From now on, run all examples in the CRA or other boilerplate environment. Place the code from this section in the src/index.js file and run the project with the npm start command.

So let’s update our app to look like a typical Tweet. We will add some HTML tags and some more text.

After saving the changes, we will see a correctly formatted Tweet on the screen – our JSX code has been converted to a correct HTML syntax.

import React from "react"; import ReactDOM from "react-dom"; ReactDOM.render( <div> <p>Hello World</p> </div> , document.getElementById('root'))

An inquisitive developer will ask why we import React if it is not used anywhere in the application code (and some IDEs may also highlight it as an error). We have to import this object, because JSX is not a syntax that can be recognized by a browser or webpack. JSX is translated into JavaScript calls.

After transforming JSX into JS we can see that our every JS tag has turned into a React.createElement call that takes three arguments:

the name of the item we render

an attribute object that we pass to the rendered item (more about this in the following chapters)

the third and subsequent parameter represent child elements

This transformation results in several important JSX limitations:

each render() call can have only one JSX element as its input parameter (but – this element can be an array of elements, or an element containing many other elements)

every character must be included in the HTML tag, so if we want to generate a space between two elements we must use notation.

Using JS in JSX syntax

In JSX code it is possible to use not only HTML string and tags (and components, as you will learn in a moment), but also JS code. We embed JS code in JSX exactly the same way as in the case of template strings – to indicate that we intend to include JS code we surround it with { } tags, and the code itself is directly invoked and it should return the value (so we can’t directly define objects, use if/else constructs, etc.).

Let’s modify our code so that the date is always up to date:

import React from "react"; import ReactDOM from "react-dom"; ReactDOM.render( <div> <time>{(new Date()).toString()}</time> <p> Hello World </p> </div> , document.getElementById('root'));

Share this: Twitter

Facebook

