Blog Home

Simple Starter Tutorial for the React JavaScript Library

In this blog post I'd like to teach you about React. React is a JavaScript library for building user interface (UI) components. It was created at Facebook, who built it to reduce the complexity of building large applications with frequently changing UI components. It is a simple, yet powerful JavaScript library that you can use to build awesome web applications.

Why am I posting a tutorial about React on a Django blog? It turns out that React and Django are a great fit together. You can learn more about how the two work together in my new React Django Guide. In this blog post I'd like to teach you about some fundamental React concepts with a simple tutorial.

Let's get started.

Step 1: Create an HTML Doc

We'll need an HTML file to do our work in. Find a directory on your computer to work in and create a file named react-101.html there. Open it for editing and type in the below code.

Save the file and load it in a browser. You should see a blank screen.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>React Tutorial</title>
    </head>
    <body>
        <div id="container"></div>
        <script src="https://fb.me/react-with-addons-0.14.2.min.js"></script>
        <script src="https://fb.me/react-dom-0.14.2.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
        <script type="text/babel">

        </script>
    </body>
</html>

Code Review
This is a standard HTML doc. Three files related to React are included: React with Addons: This is the main React library with these addons React DOM: This is an additional, required library * Babel: This library has many uses; in our app we use it to transform React code to JavaScript (that's a simplification, but will do for now)

Note that you'll want to use at least these three files when working with React.

Step 2: Create a React Component

Components are the core concept of React. Components can be equated to some logical piece of functionality on a web page. A blog page may have a React component for the blog post itself, a component for the keyword tag cloud, and maybe a component for a list of other blog posts. There's a lot of flexibility when it comes to what a component is on a web page.

Let's just create a simple component. In the react-101.html file, locate the empty <script type="text/babel"> tag and add this code. Then save the file, load it in a browser, and come back here.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<script type="text/babel">
    var App = React.createClass({
        render: function () {
            return (
                <div>
                    <h1>Hello, I'm from React code.</h1>
                </div>
            )
        }
    })
    React.render(<App />, document.getElementById('container'));
</script>

Code Review
There are two things this code does. First, it creates a React component called "App". When creating a React component you must define a render method. Here, our render method is a JavaScript function that returns some very basic HTML.

The second thing this code is call React.render(). The docs say that "React.render() instantiates the root component, starts the framework, and injects the markup into a raw DOM element, provided as the second argument."

Take note that the React.render() utility takes two arguments. First is the component name. In this case the component name is "App", which you created. The utility also takes in the HTML element that is supposed to be acted upon. In this case we have a <div id="container"> element that will be updated with the result of the React component.

Step 3: Save and Open

Save the react-101.html file and open it in a browser. You should see the text "Hello, I'm from React code." on the page.

You just built your first React app!

Step 4: Create a Nested Component

Components can be many things. You already created a component that returned a simple <h1> element. For React to be useful it needs to be able to handle any kind of HTML. Let's create a more complex component.

In the react-101.html file, update the <script type="text/babel"> section to look like the following

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<script type="text/babel">
    var Message = React.createClass({
        render: function () {
            return (
                <p>Two components combined!</p>
            )
        }
    });
    var App = React.createClass({
        render: function () {
            return (
                <div>
                    <h1>Hello, I'm from React code.</h1>
                    <Message />
                </div>
            )
        }
    })
    React.render(<App />, document.getElementById('container'));
</script>

Code Review
In the above code a new React component is created called Message. This component just returns a <p> element.

The App component is almost the same. Look at the return method. There's one change. <Message /> now appears under the header element. This demonstrates that components can be mixed

Step 5: Save and Open

Save the react-101.html file and open it in a browser. You should see the new HTML on the page.

Step 6: Working with Props

Another key React feature are "props". According to React's docs, "...props are a way of passing data from parent to child". You'll also see some sources say that props can be thought of as a way to pass properties around.

Here's a simple example of how to use props. This is just meant to demonstrate how they work. With the react-101.html file open, locate the script tag and update it to look as follows.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<script type="text/babel">
    var Message = React.createClass({
        render: function () {
            return (
                <p>Two components combined!</p>
            )
        }
    });
    var App = React.createClass({
        render: function () {
            return (
                <div>
                    <h1>Hello {this.props.name}, I'm from React code.</h1>
                    <Message />
                </div>
            )
        }
    })
    React.render(<App name="j. freddy" />, document.getElementById('container'));
</script>

Code Review
The above code should look very familiar. It's almost the same code as the previous step. However, there are a few differences.

Take a look at the React render line. It now has<App name="j. freddy" /> as the React component. The name="j. freddy" is a prop being passed to the component.

Then, take a look at the <h1>Hello {this.props.name}, I'm from React code.</h1> line. You can see how we can access the prop in the component. We need to surround it with curly braces, and then we can use the dot notation of this.props.<prop_name>.

This is a very simple example just to demonstrate that you can pass properties to components.

Step 7: Save and Open

Save the react-101.html file and open it in a browser. You should see the new HTML on the page.

Step 8: Working with State

Another concept to learn is called "state". State is another tool we can use to work with data The docs say that state "...is reserved only for interactivity, that is, data that changes over time." For example, if a component was responsible for displaying chat messages that were retrieved from a server, we would use React's state mechanism for it.

Let's take a look at how to use state. With the react-101.html file open, locate the script tag and update it to look as follows.

Notes that this is just a simple example of how state works. In a real application state would likely come from an external backend (like a RESTful API).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<script type="text/babel">
    var Message = React.createClass({
        getInitialState : function() {
            return {
                message : "This is a message showing state.",
                timestamp  : "Today!"
            };
        },
        render: function () {
            return (
                <div>
                    <p>Message: {this.state.message} </p>
                    <p>Sent: {this.state.timestamp} </p>
                </div>
            )
        }
    });
    var App = React.createClass({
        render: function () {
            return (
                <div>
                    <h1>Hello {this.props.name}, I'm from React code.</h1>
                    <Message />
                </div>
            )
        }
    })
    React.render(<App name="j. freddy" />, document.getElementById('container'));
</script>

Code Review Most of this code should look familiar. Let's focus on the new parts.

Look at the Message component. A new method called getInitialState has been defined. This method is used to populate the component with inital state. In this example, we create an object that has a message and timestamp.

Next, take a look at the Message render method. This has been updated to use the component state.

And that's how state is used!

Step 9: Save and Open

Save the react-101.html file and open it in a browser. You should see the message and timestamp added to the page.

Step 10: Work with Component Lifecycles

The last important topic we'll cover is component lifecycles. React components have a series of lifecycle events. Instead of showing you code for how this works, I recommend reading these two articles to at least get a high level understanding of how component lifecycles work.

Execution sequence of a React component’s lifecycle methods
Understanding the React Component Lifecycle

Review

Here's a nice little list keep in mind:

  • To work with React, you will need a simple HTML doc with several external JS libraries
  • At the core of React are components, which can be thought of as logical units of a user interface
  • React components can be nested to create a parent/child relationship
  • React components use a thing called props to pass datat from parent to child
  • React components have a concept called state, which is reserved for data that changes over time
  • React components have a series of lifecycle events that can be used to perform processing at different points