In this chapter, we are going to look at an overview of ReactJS—what it is and some highlights on what this powerful and flexible library does. We'll also learn how to download and make it work in a small application. In this chapter, we will cover the following topics:
Introducing ReactJS
Downloading ReactJS
Tools
Trying ReactJS
ReactJS is a JavaScript library, created by Facebook and Instagram, in order to build user interfaces (UIs) that can respond to users' input events along with creating and maintaining states. States are used to maintain changes to components, which will be covered in detail in later chapters. The page loads faster by comparing only the changed and the updated part of the web page (we will cover Virtual DOM (Document Object Model) in more detail in Chapter 4, Stateful Components and Events). React provides a one-way data flow that reduces complexity compared with a traditional data-binding system, which facilitates creating reusable and encapsulated components. We will also explore React data flow in Stateful Components and Events chapter and how to make your UI components more reusable in Chapter 7, Making Your Components Reusable.
ReactJS is not just another JavaScript library though many developers consider it to be the V of the MVC application. It drives you through building reusable components, rethinking your UI and best practices. Nowadays, performance and portability are vital to build user interfaces, mainly due to the large use of Internet-accessible devices and the fast-paced developmental phases of the projects. This can result in complex frontend code. The need for using a library that helps your code to grow in both performance and quality is really important; otherwise, you just end up writing big HTML files with UI logic everywhere that takes ages to modify and can compromise code quality. ReactJS encourages the best practices shown here:
Following a pattern
Separating concerns
Splitting your UI into components
Communication between components with one-way data flow
Use of properties and states appropriately
ReactJS is a library that takes care of the UI (Views) differently from a framework. Let's say we are building a Single Page Application (SPA) and we want to handle a routing system, we can use whatever library we want that deals with routing. This applies to every other part of the technology stack required to build a SPA except the UI or, as some say, the View, when working on an MVC/MV* architecture. In the ReactJS world, when you're talking about the view, actually you're talking about a component. They are a little different from each other. A React component holds both logic and behavior of the View. In general, a single component represents a small part of the View, whereas many of these components together represent the whole View of the application.
We will be discussing more about MVC/MV* and FLUX architecture in Chapter 6, Reacting with FLUX.
It is very straightforward to build or change just a small part of your web application. Facebook did that with their commenting interface. They replaced it with one made in ReactJS. There is detailed code at https://facebook.github.io/react/docs/tutorial.html about how the comments appear in Facebook using ReactJS.
This commenting interface, which the Facebook development team explained, gives us the live updates and Optimistic commenting, in which the comments are shown in the list before having been saved on the server. There is also a Facebook developer plugin, which enables users to add comments in your website using their Facebook accounts (https://developers.facebook.com/docs/plugins/comments).
One of my experiences was to build a survey app in ReactJS and place it in some web application already in production. ReactJS provides a bunch of life cycle events, which facilitates the integration with other libraries, plugins, and even frameworks. In Chapter 5, Component Life Cycle, we will go through all the life cycle phases of a React component, and in Chapter 7, Making Your Component Reusable, we will be incorporating validations and organizing our code using Mixins.
ReactJS understands the UI elements as objects. When building React components, we will modularize the code by encapsulating the view logic and the view representation. This is another feature that supports componentization and is one of the reasons for Virtual DOM to work. React code can also be written in another syntax, JSX (an extension to ECMASCRIPT), instead of JavaScript. Although it is not mandatory to use, it is easy to use and increases the readability of the code. We're going to dig more into JSX and see how it works and why it's necessary in Chapter 2, Exploring JSX.
ReactJS is one of the emerging JavaScript libraries to build web UI components, and some big companies are already using it in production. They are as follows:
The Instagram website
Facebook comments, page insights, business management tools, Netflix, Yahoo, Atlassian, and most new JS development
New JS development for Khan Academy, PayPal, AirBnb, Discovery Digital Networks, and many more
Some projects inside The New York Times
Before we start coding some ReactJS, we need to download it. You can download ReactJS through their website, http://facebook.github.io/react/downloads.html.
At the time of writing this book, ReactJS is currently at version 0.14.7. Two versions of ReactJS scripts are provided—one is for development, which has all the core code with comments if you want to debug or even contribute to them. The other one is for production, which includes extra performance optimizations. Here are the links of the versions of the script for downloading:
http://fb.me/react-0.14.7.js (development)
http://fb.me/react-0.14.7.min.js (production)
Versions of 0.13.0 and higher contain a huge set of enhancements. There is a support for the ES6 class syntax and removal of mix-ins, which are covered in Chapter 5, Component Life Cycle and Newer ECMAscript in ReactJS.
Inside the ReactJS downloads page, there are other versions of the ReactJS script with add-ons. This script extends the ReactJS library to support animations and transitions, and also provides some other utilities that are not part of core React. There is no need to download this version for now because we're not going to use those features in the following examples.
There is also the JSX transformer script for download. You can download it at https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js.
It should only be used in the development environment and not in production. JSX will be covered in more detail in the Chapter 2, Exploring JSX and the ReactJS Anatomy.
If you are using a tool to control your dependencies, such as Node Package Manager (NPM) or Bower, it's also possible to download ReactJS through these tools. Details can be found at https://facebook.github.io/react/downloads.html.
Check whether node
is already installed on your machine using node -v
.
Otherwise, install the node packages from their website (https://nodejs.org/en/), based on your operating system.
We cover installing packages through NPM in Chapter 8, Testing React Components and Chapter 9, Deployment.
If you have Node
and NPM configured on your machine, execute the following command inside your application's folder from any console tool to install react-tools
:
npm install react-tools
Once installed, you can reference React dependency as follows:
Var React = require('react');
From now on, you can use the React
variable and its methods, such as React.createClass({…});
. Remember that because you've installed it using NPM, it's required that you bundle your code or transform it to a static asset before testing your application. In Chapter 2, Exploring JSX, we're going to cover some transform tools that you might use. You can check for more details about deployment in Chapter 8, Preparing Your Code for Deployment.
Unlike NPM, Bower controls browser-ready packages, so it's also the same. Apart from using the NPM packages, we can also use Bower-ready packages (https://facebook.github.io/react/downloads.html). Bower helps to maintain all the packages by installing and maintaining the correct versions of the necessary packages (http://bower.io/).
First, make sure that you have Bower installed and configured. After this, execute the following command:
bower install --save react
This will save ReactJS as a dependency in you Bower configuration file. Now you just need to reference that in your HTML code. By default, it's provided at ./bower_components/react/react.js
. The minified version is also provided in the same folder at react.min.js
.
The community has already developed a bunch of tools to improve our coding experience and productivity. In this section, we'll get through some text editors, their packages, and a browser extension created to improve debugging applications in ReactJS.
Most of the text editors available today provide syntax highlighting for JSX and useful snippets and helpers for ReactJS. Here are some text editors that I suggest using:
Emacs Editor—https://www.gnu.org/software/emacs/
Sublime Text—http://www.sublimetext.com/
Atom—https://atom.io/
Brackets—http://brackets.io/
Sublime Text requires a paid license although it works in free mode, always showing a popup that might trouble you from time to time. Also, you will need to install its package manager separately. You can find sublime Text packages and more information on how to install its package manager at https://packagecontrol.io/. Once the Sublime editor is installed, go to the installed directory, and you can open Sublime from the terminal by running subl
in the directory that your are in and you will open the files of the current directory in Sublime.
Atom is recent and free and was made by GitHub. It comes with a package manager included and there is no need to install it separately. You just need to go to the settings and install the React package. It comes with syntax highlights, snippets, and so on. The only problem I've experienced using Atom on a MacOS X Yosemite is that the font quality looks poorer than that in Sublime Text. If you face it, you just need to uncheck the Use Hardware Acceleration option in Atom's settings.
Brackets is also free and has a lot of great features such as live preview; for example, you can edit your code files and see the changes being applied in the browser. Brackets has a built-in extension manager, and you can install ReactJS JSX syntax highlighting as well. However, at the time of writing this book, some highlighting features were not working well.
All of these text editors are pretty good and have lots of features, but it's not the purpose of this book to show them. Feel free to choose one if you don't have a preferred text editor already.
The ReactJS team created a browser extension for Google Chrome. It allows you to inspect the component hierarchy, and it helps a lot when you need to debug your application. You can open Chrome Web Store, search for React Developer Tools, and install it. You need to open Chrome Developer Tools (F12 on Windows and Linux, ⌘-Option-I on Mac) to use the extension. We're going to use the extension in later chapters to understand the ReactJS component hierarchy. In order to have the React extension/add-on work in Chrome/Firefox, we need to have a React component globally available on the web page.
It is time to hack some code and create our first application with ReactJS. We'll start configuring React in a simple web page by adding the ReactJS script dependency. Then, we'll create a JavaScript file that will hold our ReactJS component code and render it in an HTML element.
Then, we'll rebuild the same example using JSX syntax and learn how to configure that in the page. Don't worry about JSX for now as it will be covered in detail in the Chapter 2, Exploring JSX and the ReactJS Anatomy.
This is going to be a simple application for learning purposes. In following chapters, we're going to create a full web application that will consume the Facebook Open Graph API, log in with your Facebook's account, render your friend list, and so on. So, let's get our hands dirty!
After downloading ReactJS scripts dependencies, we need to create an HTML file with a simple element inside its body. We're going to call the file root.html.
It will be responsible for rendering our ReactJS component.
Here is how your HTML file should look like:
<!DOCTYPE html> <html> <head> <script src="http://fb.me/react-0.12.2.js"></script> </head> <body> <div id="root"></div> </body> </html>
It references Facebook CDN scripts, but you can reference the scripts that we have downloaded (fb-react-0.12.2.js
) locally.
Here is how your HTML file should look like if the locally downloaded ReactJS file is used instead of CDN:
<!DOCTYPE html> <html> <head> <script src="fb-react-0.12.2.js"></script> </head> <body> <div id="root"></div> </body> </html>
Now create a JavaScript file named hello-world.js and
reference that in the HTML file by placing this code after the root
div element:
<div id="root"></div> <script src="hello-world.js"></script>
We will make use of React.createElement to create React element. The format of React.createElement
is:
ReactElement createElement( string/ReactClass type, [object props], [children ...] )
Paste the following code into hello-world.js
:
var HelloWorld = React.createClass({ render: function () { return React.createElement('h1', null, "Hello World from Learning ReactJS"); } }); React.render( React.createElement(HelloWorld, null), document.getElementById('root') ); In the above code return React.createElement('h1', null, "Hello World from Learning ReactJS"); h1 → Is the type of HTML element to be created null → means there is no object properties presentation Third argument → the content of the h1 tag
Details of this code will be covered in more detail in the following chapters.
Now open the page in any browser and check that it created an h1
html element and placed the text inside it. You should see something like this:
Now we are going to make the same application using JSX syntax. First, we need to configure that in our HTML page by adding the JSX transformer script file JSXTransformer-0.12.2.js
after the ReactJS script react-0.12.2.js
within the head
element:
<head> <script src="http://fb.me/react-0.12.2.js"></script> <script src="http://fb.me/JSXTransformer-0.12.2.js"></script> </head>
You also need to change the hello-world.js
type reference to text/jsx
in the HTML page. It must be like this:
<script type="text/jsx" src="hello-world.js"></script>
Google Chrome doesn't accept requests to local files of type text/jsx
, it throws a cross-origin request error (commonly named as the CORS error). CORS is sharing a resource on a different domain than the current one. Chrome security doesn't allow it by default; however, you can access it on Firefox and Safari. It's also possible to work around with CORS errors by starting a local server, such as Python, Node, or any other web server you want.
Another way is to install the node package httpster
:
npm install -g httpster
Once installed, run the command httpster
from the react application directory. The application will load up in your browser (default port 3333
):
Another way is to install the simple Python server. Install it and run its command inside the folder you want to serve and then you're ready to go. You can find out how to install python at https://www.python.org/. After installing python, you can run the following command inside your project folder:
python -m SimpleHTTPServer
It will output a message saying the port it's running such as Serving HTTP
on 0.0.0.0 port 8000
. You can now navigate to http://localhost:8000/
. If this port is being used by another application, consider passing the desired port number as the last parameter in the same command as follows:
python -m SimpleHTTPServer 8080
If you don't want to use python, ReactJS has provided a tutorial page with scripts in other languages to run a simple web server and you should be able to test it. You can check it out at https://github.com/reactjs/react-tutorial/.
With our HTML page configured, we can now change the hello-world.js
script file to follow the JSX Syntax. Your script file should look like this:
var HelloWorld = React.createClass({ render: function () { return <h1>Hello World from Learning ReactJS</h1>; } }); React.render( <HelloWorld />, document.getElementById('root') );
It will generate the same result as in the previous Hello World
example. As you can see, there is no need to call the createElement
method explicitly.
Thus, the JSX will produce the same output as the JavaScript, but without the extra braces and semicolons.
In the following chapter, Chapter 2, Exploring JSX and the ReactJS Anatomy you're going to learn how JSX works and why it is highly recommended.
In this chapter, you learned what ReactJS is, downloaded it, and used it in a small application. We have created our first React component and reviewed key benefits of this powerful library.
In the next chapter, we are going to dive into JSX and learn how to build some practical components that demonstrate this powerful extension syntax. We'll also learn some "gotchas" and best practices and learn why JSX suits our needs when developing a React components presentation.