Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Getting Started with React
Getting Started with React

Getting Started with React: A light but powerful way to build dynamic real-time applications using ReactJS

By Doel Sengupta , Manu Singhal , Danillo Corvalan
€22.99 €15.99
Book Apr 2016 212 pages 1st Edition
eBook
€22.99 €15.99
Print
€28.99
Subscription
€14.99 Monthly
eBook
€22.99 €15.99
Print
€28.99
Subscription
€14.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Apr 29, 2016
Length 212 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781783550579
Vendor :
Facebook
Category :
Table of content icon View table of contents Preview book icon Preview Book

Getting Started with React

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.

Left arrow icon Right arrow icon

Key benefits

  • Learn how to develop powerful JavaScript applications using ReactJS
  • Integrate a React-based app with an external API (Facebook login) while using React components, with the Facebook developer app
  • Implement the Reactive paradigm to build stateless and asynchronous apps with React

Description

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.

What you will learn

[*] Understand the ReactJS basics through an overview [*] Install and create your first React component [*] Refactor the ReactJS component using JSX [*] Integrate your React application with the Facebook login and Graph API, then fetch data from your liked pages in Facebook and display them in a browser [*] Handle UI elements events with React, respond to users input, and create stateful components [*] Use some core lifecycle events for integration and find out about ES6 syntaxes in the React world [*] Understand the FLUX architecture and create an application using FLUX with React [*] Make a component more reusable with mixins and validation helpers and structure your components properly [*] Explore techniques to test your ReactJS code [*] Deploy your code using webpack and Gulp

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Apr 29, 2016
Length 212 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781783550579
Vendor :
Facebook
Category :

Table of Contents

18 Chapters
Getting Started with React Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Authors Chevron down icon Chevron up icon
Acknowledgments Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
Getting Started with ReactJS Chevron down icon Chevron up icon
Exploring JSX and the ReactJS Anatomy Chevron down icon Chevron up icon
Working with Properties Chevron down icon Chevron up icon
Stateful Components and Events Chevron down icon Chevron up icon
Component Life cycle and Newer ECMAScript in React Chevron down icon Chevron up icon
Reacting with Flux Chevron down icon Chevron up icon
Making Your Component Reusable Chevron down icon Chevron up icon
Testing React Components Chevron down icon Chevron up icon
Preparing Your Code for Deployment Chevron down icon Chevron up icon
What's Next Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.