Home Web Development Getting Started with React

Getting Started with React

By Doel Sengupta , Manu Singhal , Danillo Corvalan
books-svg-icon Book
eBook $29.99 $20.98
Print $38.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $29.99 $20.98
Print $38.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started with ReactJS
About this book
ReactJS, popularly known as the V (view) of the MVC architecture, was developed by the Facebook and Instagram developers. It follows a unidirectional data flow, virtual DOM, and DOM difference that are generously leveraged in order to increase the performance of the UI. Getting Started with React will help you implement the Reactive paradigm to build stateless and asynchronous apps with React. We will begin with an overview of ReactJS and its evolution over the years, followed by building a simple React component. We will then build the same react component with JSX syntax to demystify its usage. You will see how to configure the Facebook Graph API, get your likes list, and render it using React. Following this, we will break the UI into components and you’ll learn how to establish communication between them and respond to users input/events in order to have the UI reflect their state. You’ll also get to grips with the ES6 syntaxes. Moving ahead, we will delve into the FLUX and its architecture, which is used to build client-side web applications and complements React’s composable view components by utilizing a unidirectional data flow. Towards the end, you’ll find out how to make your components reusable, and test and deploy them into a production environment. Finally, we’ll briefly touch on other topics such as React on the server side, Redux and some advanced concepts.
Publication date:
April 2016
Publisher
Packt
Pages
212
ISBN
9781783550579

 

Chapter 1. Getting Started with ReactJS

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

 

Introducing 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.

Note

MVC stands for Model View Controller and MV* for Model View Whatever.

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.

Who uses ReactJS?

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

 

Downloading ReactJS


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:

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.

Installing ReactJS with NPM

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.

Installing ReactJS with Bower

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.

 

Tools


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.

Text editors

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:

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.

Chrome extension

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.

 

Trying ReactJS


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!

Configuring ReactJS in a web page

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>

Creating your first React component

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:

Configuring JSX

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>

Serving files through the web server

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/.

Creating a React component with the JSX syntax

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.

 

Summary


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.

About the Authors
  • Doel Sengupta

    Doel Sengupta is a software programmer and is working in the industry for over 7 years, as a DevOps engineer and as a developer building enterprise level Web and mobile applications using RubyonRails and Rhomobile, Chef. Currently she is exploring the Javascript ecosystem. She has been a speaker in Ruby conferences. She finds interest in life sciences and has publications of her work in customised human joint prostheses design using Ansys & Mimics. She is an avid blogger (www.doels.net) writing about her technical and not-so-technical passions like culinary, photography, films. Follow her on twitter @doelsengupta.

    Browse publications by this author
  • Manu Singhal

    Manu Singhal has been a programmer for 8 years and loves to code on Ruby and React. These days, he is busy cofounding a startup in e-commerce. In earlier roles, he has developed many enterprise and consumer based web/mobile applications and has also been a speaker at Ruby Conferences in India and the USA. He never misses a chance to play tennis and go hiking. He has worked with Tata Consultancy Services and McKinsey & Company as a software developer and an architect. He has contributed in books on Rhomobile and RubyMotion by Packt earlier.

    Browse publications by this author
  • Danillo Corvalan

    Danillo Corvalan is a software engineer who is passionate about software patterns and practices. He has a keen interest in the rapidly changing world of software development. He is quite insistent about the need of fast and reliable frameworks. He is originally from Brazil, now living in Amsterdam, the Netherlands. He loves biking a lot. In Brazil, he worked on applications for the general public and lawyers, at the Court of Justice in his hometown city, Cuiab/MT. Then, he moved to Florianpolis/SC, and worked at Bravi Software for developing hybrid and responsive web apps for education. Now, in Amsterdam, he is working at Vigour.io and helping to develop live multiscreen and responsive apps. From the web client-side perspective, in general, he has been in touch with technologies, such as vanilla JavaScript, jQuery, Backbone, and ReactJS. For the past 5 years, Danillo has also worked with open source platforms and JavaScript on the server side (Node.js). He has played with React Native in order to develop native mobile applications with ReactJS.

    Browse publications by this author
Latest Reviews (2 reviews total)
Even though I've bought several books through Packt this purchase has by far been the worst. Each successive chapter doesn't actually build upon the code from the previous chapter. And to make it worse, the chapter doesn't tell you that the code you'll be working with in that chapter has nothing to do with the previous chapter's code. Even though you're supposed to be building some app throughout the whole book, the first several chapters don't seem to actually be doing this. As the reader, you are left trying to figure out which code you are actually supposed to be using. Then there's the fact that the code samples in the chapters are full of errors. If you're new to React then trying to figure out what you did wrong if you typed in the code samples yourself is not conducive to learning React. At one point, several chapters in I decided to stop typing in the code samples and just download the code examples from the Packt website. I thought that this would allow me to really follow along and finally really start learning React. I couldn't have been more wrong. I downloaded the code just fine but when I went to look at the code for the chapter I was on at the time the code did not match what was being talked about in the chapter. I was even more lost than I had been. I even went to some of the earlier chapters I had already done and tried to run that code and I couldn't get it to work. I did complain to Packt about this and so maybe by the time someone else gets this book some of these issues, especially the code examples that can be downloaded, will be fixed. I don't know. At this time I cannot recommend anyone to buy this book to learn React.
The book is very good at getting up to speed with React. I have more than 20 years of experience developing software, but did not do any React systems before reading this book. This book introduces the concepts at a good pace without rushing things, nor dumbing you down. I've checked other introductory books on React and they try to force you to use a particular development stack without doing a proper introduction to each piece of software. So you end up confused as to exactly what is the role played by each part. This book does not fall into this trap. And you have a clear understanding of the role played by each component. You're in a much better position to decide whether or not you want to use, ditch or replace each components introduced. It's the best introduction book on React I could find.
Getting Started with React
Unlock this book and the full library FREE for 7 days
Start now