Introduction to React

React is a JavaScript library that is primarily responsible for handling the “view” component of a JavaScript single-page application. As it describes itself of the React homepage…

Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it’s easy to try it out on a small feature in an existing project.

React’s focus, first and foremost, has to do with rendering dynamic UIs in a manner that is visually appealing to the user. It is flexible enough that it can be used in a diversity of capacities and contexts. We mentioned earlier that there are a number of different MVW/MV* JavaScript frameworks and all of them have different implementations in how they handle the various aspects of a JavaScript application. Naturally they all have different ways that they handle rendering visual representations of the data that the application is handling. Backbone.js natively uses Underscore.js templates, Ember users Handlebars.js, and Knockout.js and Angular have their own syntax. With a little bit of work you can swap view engines within these frameworks if you so choose. And it would be here where we could incorporate React to handle the view rendering portion of an application. But, as mentioned above, React is not dependent on any JavaScript framework being in place. It can be used as a standalone aspect of an application almost entirely independent from any other library or environment.

So why go to the trouble to incorporate React? Why not just use a framework’s native rendering engine (if you are using a framework). If you are not using a framework, why not just use something like jQuery to handle your view layer? Again, looking at the React homepage, the following description is provided…

React abstracts away the DOM from you, giving a simpler programming model and better performance. React can also render on the server using Node, and it can power native apps using React Native.

As it turns out there are a number of different positive aspects in terms of performance, scalability, and simplicity that React can provide to application development as it progresses along in both size and complexity. We will explore these in detail as we go forward. As many have noticed, React is a little bit unorthodox from “traditional” JavaScript application development (if there were such a thing) and it can take a little bit of working with it and a little bit of trial and error before many of the benefits of it are fully realized. Indeed, many developers admit that they did not quite “get it” at first and some have even described a substantial initial aversion to some of its implementations. So if you experience this on any level, you are definitely not alone and I would merely invite you to “stick with it” through some of the initial tutorials before you run for the hills screaming in terror. Who knows? You just might be surprised at the end of the day.

Note: For the following discussions want to run our various projects inside of a localhost HTTP web server. If you have a local Apache or IIS setup you may wish to use this by putting the files that you create in the upcoming tutorials in a directory created inside the www folder. Another quick easy implementation is to just pull down the Node.js http-server module by running the following from your command line…

$ npm install -g http-server

From there you can create a directory anywhere you like and run the following…

$ http-server

This will run an HTTP server at localhost:8080. If you got to https://localhost:8080 you should see something there that tells you a server is running.

React is a view rendering JavaScript library that is created and maintained by a team of engineers at Facebook. It is responsible for dynamically handling the visual display of various components within a web site or web application in a flexible, efficient, and interactive manner. What this often means is that React handles the displaying of the data that underlies an application and will dynamically update everything that it needs to in a performance conscious manner when that data changes. We will look at all of React’s various components that come together to make this happen in greater detail as we go along in the upcoming tutorials.

Perhaps the best thing to do is to jump right in and get our first look at React. To start out we will need an index.html file. So create a new file in a directory where you want to run things from and create a file called index.html. In this file place the following code…

<!DOCTYPE html>
<html>
<head>
    <title>React</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>        
    <script src="https://fb.me/react-0.12.2.js"></script>
    <script src="https://fb.me/JSXTransformer-0.12.2.js"></script>

</body>
</html>

So we are first loading up the React library over CDN and we are also loading up something called the “JSXTransformer.” React has its own programming language called JSX. It is React’s own special easy-to-read abstracted syntax that in the end gets converted to native JavaScript. It is important to note that using JSX is optional. It is not required to create React applications and you can write your React components in native JavaScript if you so choose. For a lot of the upcoming examples provided in what is to follow, we will look at the same code written in both JSX and native JavaScript and you can decide which is more appealing to you. We will discuss the pros and cons of leveraging JSX bit later on as well.

Hello World in React

So now that we have React loaded up, let’s write our first React component. We will do the obligatory “Hello World” example that has so ubiquitous throughout programming tutorials since the dawn of time. We are going to personalize this a bit more though and we are going to say “hello” to an individual rather than the entire world.

JSX

So let’s start by looking at the JSX syntax just to get a look at it. Create a folder called “js” and create a file called hello.jsx and include it after the scripts like so…

<!DOCTYPE html>
<html>
<head>
    <title>React</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>        
    <script src="https://fb.me/react-0.12.2.js"></script>
    <script src="https://fb.me/JSXTransformer-0.12.2.js"></script>
    <script type="text/jsx" src="js/hello.jsx"></script>
</body>
</html>

In this file add the following JSX code…

var HelloMessage = React.createClass({
    render: function() {
        return <div>Hello {this.props.name}</div>;
    }
});

React.render(<HelloMessage name="John" />, document.body);

Now let’s open this index.html in your favorite browser in your web server. You should see the message “Hello John” displayed. Congratulations, you have just written your first React component!

React components implement a render() method that takes input data and returns what to display. When we are calling React.render the first argument we are passing in specifies the name of the component to render and the properties that we want to pass in. The second parameter in React.render is a JavaScript object of the element that we want to append our element inside of. Indeed if we use our developer tools to inspect the source, we see our message inside a <div> inside the <body> (with some additional React wrapper elements).

You can play around with this a little bit. Try changing the <div> to a <p> or change the name from John to your own name to see the changes reflected in the code.

JavaScript

So now let’s take a look and see what it would look like to write a React component in native JavaScript. Change the HTML to point to a .js file instead of a .jsx file. We also do not need the JSX Transformer file any more since we are not working with JSX in this instance.

<!DOCTYPE html>
<html>
<head>
    <title>React</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>        
    <script src="https://fb.me/react-0.12.2.js"></script>
    <script type="text/javascript" src="js/hello.js"></script>
</body>
</html>

Create a file called “hello.js” in our “js” folder and in this file place the following code…

var HelloMessage = React.createClass({displayName: "HelloMessage",
    render: function() {
        return React.createElement("div", null, "Hello ", this.props.name);
    }
});

React.render(React.createElement(HelloMessage, {name: "John"}), document.body);

And again, open this index.html file in your favorite browser. We should see the same “Hello John”. So as we can see here, we are doing something similar in that we are still calling React.render, but we need to add some additional code in a couple of places in calling React.createElement. So things are a little bit more verbose in doing things the native JavaScript way, but ultimately this is the code that JSX gets converted to before it runs. So the choice regarding which of these you prefer is really up to you. The differences between the two approaches seem relatively minor, but as your applications grow in both size and complexity JSX can end up being a lot more succinct which can reduce the number of lines of code that you need to write and sort through.

Note too that there are tools that will do the JSX conversion to JavaScript for you. For example, if you copy and paste your components into this online JSX compiler it will be automatically converted to native JavaScript. So it really might be worth your while to take a look at JSX as a solution for developing your applications.

Displaying Data

Let’s try to create a React application that is a little bit more complex. In what follows we will pass a set of data into our React component and iterate through it. Create a new index.html file and add the following code

<!DOCTYPE html>
<html>
<head>
    <title>React</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
        
    <script src="https://fb.me/react-0.12.2.js"></script>
    <script src="https://fb.me/JSXTransformer-0.12.2.js"></script>
    <script type="text/jsx" src="jsx/notes.jsx"></script>  
    <script type="text/jsx" src="jsx/app.jsx"></script>  
	
</body>
</html>

In our “jsx” create a “notes.jsx” file and an “app.jsx” file. In our notes.jsx file add the following code…

var NotesList = React.createClass({
    render: function () {
        var notes = this.props.notepad.notes;
    
        return (
            <div className="note-list">
            {
                notes.map(function (note) {
                    var title = note.title || note.content;
                    var content = (!note.title) ? '' : note.content;
                    return (<div key={note.id} className="note-summary"><h2>{title}</h2><p>{content}</p></div>);
                })
            }
            </div>
        );
    }
});

So here we can see our “NotesList” component. The data that gets passed in to any React component is available on the “props” object. The format goes this.props.attribute where “attribute” is the name of the attribute. So in our example it is called “notepad”. So when we call our render function, it will look like the following…

React.render(<NotesList notepad={notepadObject}/>, document.body);

The value “notepadObject” can be any JavaScript type… a string, object literal, array, or whatever else. We access it inside our component with this.props. So when we say this.props.notepad.notes it means we are expecting notepadObject to have a “notes” property on it. In a production grade application it would probably be best practice to do some checking/error handling against this, but for this simple example we will omit it for now.

Because we are calling the map function on the notes property we are expecting this to be an array. We will iterate through this array and render out a title and some content. If there is no title, we will set the content to the title which is what the tertiary expression handles.

So we can implement this to see what this looks like in practice. So in our app.jsx file we can add the following code…

var notepadObject = {
    notes: [{
        id: 1,
        title: "Eat Breakfast",
        content: "Toast and scrambled eggs would be nice"
    },
    {
         id: 2,
         content: "Walk Dog"
    },
    {
         id: 3,
         title: "Learn React",
         content: "I am making great progress!"
     }]
};

React.render(<NotesList notepad={notepadObject}/>, document.body);

As we expected, our React component takes in a “notepadObject” object that has a “notes” property containing an array of objects. We iterate through the array and display the various values set in each object. For the second one, because there is no title, we just use that as the title. If we run this in our local web server, we can see the results.

Let’s take a quick look at how this would look in native JavaScript. Like with our earlier example, it will be slightly different but still recognizable as to what the code is doing. As before we will load JavaScript instead of JSX.

<!DOCTYPE html>
<html>
<head>
    <title>React</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
        
    <script src="https://fb.me/react-0.12.2.js"></script>
    <script type="text/javascript" src="js/notes.js"></script>  
    <script type="text/javascript" src="js/app.js"></script>  
	
</body>
</html>

Below is the code found in notes.js…

var NotesList = React.createClass({displayName: "NotesList",
    render: function () {
        var notes = this.props.notepad.notes;
    
        return (
            React.createElement("div", {className: "note-list"}, 
            
                notes.map(function (note) {
                    var title = note.title || note.content;
                    var content = (!note.title) ? '' : note.content;
                    return (React.createElement("div", {key: note.id, className: "note-summary"}, React.createElement("h2", null, title), React.createElement("p", null, content)));
                })
            
            )
        );
    }
});

And in app.js

var notepadObject = {
    notes: [
        {
            id: 1,
            title: "Eat Breakfast",
            content: "Toast and scrambled eggs would be nice"
        },
        {
            id: 2,
            content: "Walk Dog"
        },
        {
            id: 3,
            title: "Learn React",
            content: "I am making great progress!"
        },

    ]
};

React.render(React.createElement(NotesList, {notepad: notepadObject}), document.body);

So again here we have a similar but slightly more verbose set of code when we use the native JavaScript as opposed to JSX. If we run this example, the final result is the same.

Summary

So this concludes our very brief and succinct introduction to React. We have only just scratched the surface with some basic rendering of data coming from our React component. In upcoming discussions, we will explore the more complex and more dynamic features that React can give us and we will see where the value of this library really emerges. But our journey has started out with a few small steps that we can build upon from here.

, , , , , , 9bit Studios E-Books

Like this post? How about a share?

Stay Updated with the 9bit Studios Newsletter

0 Responses to Introduction to React

    Leave a Reply

    Your email address will not be published. Required fields are marked *