Learning Management Platform for Written Tutorial Series.

React JSX

React JSX

Introduction

This tutorial is the third part of a series to get up and running with ReactJS, here we will learn how to use JSX syntax to render HTML elements to the browser. JSX allows us to use XML like opening and closing tags to define HTML elements.

The image below shows you how sample JSX code looks like.

ReactJS JSX

Topics to be covered

We will cover the following topics in this tutorial

  • Tutorial pre-requisites
  • What is JSX
  • JSX Compiler
  • JSX Syntax
  • JSX Example
  • Precompiling JSX

Tutorial pre-requisites

For you to complete this tutorial successfully, you will need to at least know / have the following.

  • Web server – you can still run React code without a web server but then you will not be able to use extensions such as react-detector as they require the http protocol.
  • You should be familiar with HTML, CSS and JavaScript basics.
  • You should be familiar with the basics of ReactJS. If you are not familiar with the basics, read the previous tutorials.
  • You should have text editor or Integrated Development (IDE) that supports HTML, CSS and JavaScript
  • An update to date browser that has JavaScript enabled. Google chrome is highly recommended since we will be using Google Chrome extensions to debug the code. You can also use other browsers such as Firefox and download the appropriate React Developer Add-ons.
  • You have a command line tool or terminal and you know the basics

What is JSX?

JSX stands for JavaScript XML, It is a way for us to write JavaScript in XML syntax, you are probably saying to yourself, what! I don't know XML. That is ok, it looks like HTML and you will see that more relevant as we go on.

JSX Compiler

A JSX compiler is used to convert JSX into JavaScript code. In development mode, we will use Babel. Babel will convert our JSX syntax into JavaScript at runtime. You should not use this in production mode. This is only intended for quick development purposes. Using Babel in production mode slows down the system. It is recommended to pre-compile JSX into JavaScript code in production mode.

The official website for Babel is https://babeljs.io/ . I recommend you visit their official website for more details.

JSX Syntax

On the script tag containing our React application we will add a type attribute and set it to type="text/babel", It will tell the compiler to convert whatever is contained inside the script tag. We will also need to include the babel-core JavaScript file

The following code shows the basic JSX syntax.

var componentName = React.createClass({ 
    render: function() { 
        return (
            <div>
                <h1>...</h1>
                <p>...</p>
            </div>
            );
    }
}); 

ReactDOM.render(<componentName/>, document.getElementById('react-target'));

HERE,

  • var componentName defines a variable that will store our ReactJS component
  • React.createClass({…}); instantiates a React component
  • render: function() {…} the render anonymous function is used to output HTML content into the web browser.
  • Return (html components)contains the HTML content that we would like to output in the web browser.

JSX Example

Let’s now look at a simple JSX example.

Create a new file jsx.html in the web project directory reactjs-example.

Add the following code.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>React Basic Kode</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>

<body>
    <div class="container">
        <h1>React Example Basic Kode Blog</h1>
        <div/>
        <div id="react-target">
            <p>
                React should start working in a few milli seconds
            </p>
            <p>
                If you can see this, React is not working right.
            </p>
        </div>

        <script src="https://fb.me/react-0.14.6.js"></script>
        <script src="https://fb.me/react-dom-0.14.6.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
        <script type="text/babel">

            var Hello = React.createClass({ render() { return (
            <div>
                <h1>Hello from Kode</h1>
                <p>Maybe you prefer a hello from Adele</p>
            </div>
            ) } }); 

            ReactDOM.render(<Hello/>, document.getElementById('react-target'));
        </script>

</body>
</html>

HERE,

  • <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script> loads the babel-core file
  • <script type="text/babel">…</script> creates a script file of type text/babel. This attribute will be used by babel to convert our JSX code into JavaScript code at runtime.

Open your web browser and load the URL that points to the jsx.html file.

You will get results similar to the following

ReactJS JSX Example

This is how our Hello component looks like in the React Developer Tool, as you can see on the left hand side we have an element tag called Hello which is holding the elements we have rendered to the screen.

Precompiling JSX

JSX makes it easier to create complex user interfaces but compiling it at runtime in production slows down the performance of our React applications. Precompiling JSX into JavaScript before deployment solves this problem.

We will use babel command line utility to compile our JSX code into JavaScript code. We will use NodeJS Package Manager (NPM) to install babel cli. If you do not have NPM already installed, you can download NodeJS from the official website https://nodejs.org/en/ and install it.

Let’s now check to see if NPM was installed successfully

Open the command prompt / terminal

npm --v

The above command will output the version number of NPM that you have installed.

Let’s now install babel-cli and some presets

Run the following commands

npm install -g babel-cli 
npm install babel-preset-es2015 babel-preset-react

The above commands will install all the packages required to precompile JSX into JavaScript. The above example used inline JSX scripts. We will now move the inline script into its own separate file.

Create a new directory src in reactjs-example directory

Create a new file hello.jsx inside src directory

Add the following code to hello.jsx

var Hello = React.createClass({ 
    render: function() { 
        return (
            <div>
                <h1>Hello from Kode</h1>
                <p>Maybe you prefer a hello from Adele</p>
            </div>
            );
    }
}); 

ReactDOM.render(<Hello/>, document.getElementById('react-target'));

Let’s now precompile the above JSX code

Create a new directory lib in reactjs-example

Create a new file .babelrc in the root directory of reactjs-example

Add the following code to .babelrc file

{
  "presets": ['react']
}

Open the command prompt / terminal

Browse to the root directory of the project. If you are using XAMPP on windows and its installed to drive C, you can run the following command

cd C:\xampp\htdocs\reactjs-example

Run the following command to watch the src directory and compile .jsx files in it into .js files in the lib directory.

babel --presets es2015,react --watch src/ --out-dir lib/

HERE,

• The above babel command uses es2015 and react presets to watch the contents of *.jsx files in src directory. If any of the *.jsx files are detected, they will be converted into *.js file and stored in the lib directory. If you make any changes to the source file, the watch command will detect the changes and automatically compile them for you.

After running the above command, you should be able to see hello.js file in the lib directory.

Open hello.js, you will get the following code

'use strict';

var Hello = React.createClass({
    displayName: 'Hello',

    render: function render() {
        return React.createElement(
            'div',
            null,
            React.createElement(
                'h1',
                null,
                'Hello from Kode'
            ),
            React.createElement(
                'p',
                null,
                'Maybe you prefer a hello from Adele'
            )
        );
    }
});

ReactDOM.render(React.createElement(Hello, null), document.getElementById('react-target'));

Let’s now create a new file jsx2.html that will use the JavaScript file hello.js without include babel-core

Add the following code to jsx2.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>React Basic Kode</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>

<body>
    <div class="container">
        <h1>React Example Basic Kode Blog</h1>
        <div/>
        <div id="react-target">
            <p>
                React should start working in a few milli seconds
            </p>
            <p>
                If you can see this, React is not working right.
            </p>
        </div>

        <script src="https://fb.me/react-0.14.6.js"></script>
        <script src="https://fb.me/react-dom-0.14.6.js"></script>
        <script src="lib/hello.js"></script>

</body>
</html>

As you can see from the above code, we did not include babel-core or any text/babel attribute. We simply included a regular JavaScript file.

View jsx2.html in the web browser. You will get the same results as the first example but in terms of performance, the second example will load faster.

Summary

JSX is a power syntax that simplifies writing code that renders HTML elements in the browser. Babel is used to compile JSX into JavaScript code. You can use runtime compilation during development but it is recommended to precompile JSX into JavaScript before deployment.

What’s next?

In the next tutorial, we will introduce you to React Components. JSX syntax. JSX is a JavaScript syntax extension that looks similar to XML.

If you found this tutorial useful, support us by using the social media buttons to like and share the tutorial. If you didn’t find it useful, please use the comments section below to let us know how we can do better next time.

Each week, a new ReactJS tutorial is added to our collection. Subscribe to our newsletter, like our Facebook fan page or follow us on Twitter to get free updates when the collection is updated.

Tutorial History

Tutorial version 1: Date Published 2016-02-02


...