Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
ReactJS by Example - Building Modern Web Applications with React
ReactJS by Example - Building Modern Web Applications with React

ReactJS by Example - Building Modern Web Applications with React: Building Modern Web Applications with React

eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

ReactJS by Example - Building Modern Web Applications with React

Chapter 2. JSX in Depth

In the first chapter, we built our first component using React. We saw how using JSX makes the development easy. In this chapter, we will dive deep into JSX.

JavaScript XML (JSX) is an XML syntax that constructs the markup in React components. React works without JSX, but using JSX makes it easy to read and write the React components as well as structure them just like any other HTML element.

In this chapter, we will cover following points:

  • Why JSX?
  • Transforming JSX into JavaScript
  • Specifying HTML tags and React components
  • Multiple components
  • Different types of JSX tags
  • Using JavaScript expressions inside JSX
  • Namespaced components
  • Spread attributes
  • CSS styles and JSX
  • JSX Gotchas

At the end of the chapter, we will get familiar with the JSX syntax, how it should be used with React, and best practices of using it. We will also study some of the corner cases that one can run into while using JSX.

Why JSX?

Shawn had a great first day and he was just getting started with the next one at Adequate Consulting. With a mug of coffee, he startled Mike.

"Hey Mike, I saw that we used JSX for building our first component. Why should we use JSX when React has React.createElement?"

"You can use React without using JSX. But JSX makes it easy to build React components. It reduces the amount of code required to write. It looks like HTML markup. Its syntax is simple and concise and it's very easy to visualize the components that are getting built."

"Take an example of the render function of a component without using JSX."

// render without JSX
render: function(){
    return(React.createElement("div", 
                               null, 
                               "Hello React World!"));
}

"With JSX, it looks much better."

// render with JSX
render: function(){
    return <div>
      Hello React World
    </div>;
  }

&quot...

Transforming JSX into JavaScript

"Shawn, as I mentioned, the JSX is transformed to the native JavaScript syntax."

// Input (JSX):
var app = <App name="Mike" />;

"This will eventually get transformed to"

// Output (JS):
var app = React.createElement(App, {name:"Mike"});

Tip

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  • Log in or register to our website using your e-mail address and password.
  • Hover the mouse pointer on the SUPPORT tab at the top.
  • Click on Code Downloads & Errata.
  • Enter the name of the book in the Search box.
  • Select the book for which you're looking to download the code files.
  • Choose from the drop-down menu where you purchased this book from.
  • Click on Code...

HTML tags vs React components

"Mike, I am intrigued by one more thing. In JSX, we are mixing the React components as if they are simple HTML tags. We did this in our first component."

ReactDOM.render(<App headings = {['When', 'Who', 'Description']} 
                     data = {data} />, 
             document.getElementById('container'));

"The App tag is not a valid HTML tag here. But this still works."

"Yes. That's because we can specify both HTML tags and React components in JSX. There is a subtle difference though. HTML tags start with a lowercase letter and React components start with an uppercase letter." Mike explained.

// Specifying HTML tags
render: function(){
    return(<table className = 'table'>
           .....
           </table>);
}

// Specifying React components
var App = React.createClass({..});
ReactDOM.render(<App headings = {['When', 'Who', &apos...

Self closing tag

"Another thing that you must have noticed is how the component tag is closed in ReactDOM.render" added Mike.

ReactDOM.render(<App .../>, document.getElementById('container'));

"As JSX is based on XML, it allows adding a self-closing tag. All the component tags must be closed either with self-closing format or with a closing tag."

"Thanks Mike! Things make much more sense now."

Why JSX?


Shawn had a great first day and he was just getting started with the next one at Adequate Consulting. With a mug of coffee, he startled Mike.

"Hey Mike, I saw that we used JSX for building our first component. Why should we use JSX when React has React.createElement?"

"You can use React without using JSX. But JSX makes it easy to build React components. It reduces the amount of code required to write. It looks like HTML markup. Its syntax is simple and concise and it's very easy to visualize the components that are getting built."

"Take an example of the render function of a component without using JSX."

// render without JSX
render: function(){
    return(React.createElement("div", 
                               null, 
                               "Hello React World!"));
}

"With JSX, it looks much better."

// render with JSX
render: function(){
    return <div>
      Hello React World
    </div>;
  }

"Compared to the previous non-JSX example, the JSX code is much more readable...

Transforming JSX into JavaScript


"Shawn, as I mentioned, the JSX is transformed to the native JavaScript syntax."

// Input (JSX):
var app = <App name="Mike" />;

"This will eventually get transformed to"

// Output (JS):
var app = React.createElement(App, {name:"Mike"});

Tip

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  • Log in or register to our website using your e-mail address and password.

  • Hover the mouse pointer on the SUPPORT tab at the top.

  • Click on Code Downloads & Errata.

  • Enter the name of the book in the Search box.

  • Select the book for which you're looking to download the code files.

  • Choose from the drop-down menu where you purchased this book from.

  • Click on Code Download.

Once the file is downloaded, please...

HTML tags vs React components


"Mike, I am intrigued by one more thing. In JSX, we are mixing the React components as if they are simple HTML tags. We did this in our first component."

ReactDOM.render(<App headings = {['When', 'Who', 'Description']} 
                     data = {data} />, 
             document.getElementById('container'));

"The App tag is not a valid HTML tag here. But this still works."

"Yes. That's because we can specify both HTML tags and React components in JSX. There is a subtle difference though. HTML tags start with a lowercase letter and React components start with an uppercase letter." Mike explained.

// Specifying HTML tags
render: function(){
    return(<table className = 'table'>
           .....
           </table>);
}

// Specifying React components
var App = React.createClass({..});
ReactDOM.render(<App headings = {['When', 'Who', 'Description']}  
                     data = {data} />, 
                document.getElementById('container...

Self closing tag


"Another thing that you must have noticed is how the component tag is closed in ReactDOM.render" added Mike.

ReactDOM.render(<App .../>, document.getElementById('container'));

"As JSX is based on XML, it allows adding a self-closing tag. All the component tags must be closed either with self-closing format or with a closing tag."

"Thanks Mike! Things make much more sense now."

Multiple components


"Shawn, let's get back to our application. We are using almost the same code from last time but you can set up a new JSBin. We have included the latest React library and bootstrap library in the HTML tab. We have also added a container element, which we will render our React app."

<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery.min.js"></script>
    <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
    <script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
    <script src="//fb.me/react-with-addons-0.14.3.js"></script>
    <script src="//fb.me/react-dom-0.14.3.js"></script>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JSX in Detail</title>
  </head>
  <body...

JavaScript expressions


"Shawn, let's discuss a bit about how we have rendered the Rows and Headings tag."

render: function() {
    var headings = this.props.headings.map(function(name) {
      return(<Heading heading = {name}/>);
    });

   return <tr>{headings}</tr>;
  }

"We are rendering {headings}, which is a list of React components, directly by adding them in curly braces as children of the <tr> tag. These expressions that are used to specify the child components are called child expressions."

"There is another category of expressions called as JavaScript expressions. These are simple expressions used for passing props or evaluating some JavaScript code that can be used as an attribute value."

// Passing props as expressions
ReactDOM.render(<App headings = {['When', 'Who', 'Description']} 
                  data = {data} />, 
                document.getElementById('container'));

// Evaluating expressions
ReactDOM.render(<App headings = {['When', 'Who...

Namespaced components


"Shawn, you must have used modules and packages in languages such as Ruby and Java. The idea behind these concepts is to create a namespace hierarchy of code such that the code from one module or package doesn't interfere with another."

"Yes. Is something like this available with React?" Shawn asked.

"Yes. React allows creating components that are namespaced under a parent component so that they don't interfere with other components or global functions."

"We are using very generic names such as Rows and Headings that can be used later in other parts of the app too. So it makes sense to namespace them now, rather than later." explained Mike.

"Agreed. Let's do it right away," Shawn.

"We need to represent the top-level component as custom component rather than using the <table> element."

var RecentChangesTable = React.createClass({
  render: function() {
    return <table>
             {this.props.children}
           </table>;
  } 
});

"Now, we can replace...

Spread attributes


Shawn learned a lot of things about JSX but when he was reflecting on the previous steps, he came up with another question.

"Mike, as of now we are just passing two props to the App component: headings and changesets. However, tomorrow these props can increase to any number. Passing them one by one would be cumbersome. Especially, when we have to pass some data from the recent changes API directly. It will be hard to a keep track of the structure of the incoming data and pass it accordingly in the props. Is there a better way?"

"Another excellent question, Shawn. True, it might be cumbersome passing a large number of attributes to the component one by one. But we can solve this using the spread attributes."

var props = { headings: headings, changeSets: data, timestamps: timestamps };
ReactDOM.render(<App {...props } />, 
                     document.getElementById('container'));

"In this case, all the properties of object are passed as props to the App component. We...

Styles in JSX


"Mike, all of the things that we did today are very cool. When do we start adding styles? How can I make this page look pretty? Right now it's a bit dull." Shawn asked.

"Ah, right. Let's do that. React allows us to pass styles to the components the same way props can be passed. For example, we want our headings to be of the floral white color and maybe we want to change the font size. We will represent it in a typical CSS way as follows:"

background-color: 'FloralWhite',
font-size: '19px';

"We can represent this as a JavaScript object in the CamelCase fashion."

    var headingStyle = { backgroundColor: 'FloralWhite',
                         fontSize: '19px' 
                       };

Then, we can use it in each Heading component as a JavaScript object."

RecentChangesTable.Heading = React.createClass({
  render: function() {
    var headingStyle = { backgroundColor: 'FloralWhite',
                         fontSize: '19px' };
    return(<th style={headingStyle}>{this.props.heading...
Left arrow icon Right arrow icon

Key benefits

  • Create pragmatic real-world applications while learning React and its modern developer tools
  • Build sustainable user interfaces by transforming data into components of UI
  • Learn how to generate reusable ReactJS components effectively

Description

ReactJS is an open-source JavaScript library that brings the power of reactive programming to web applications and sites. It aims to address the challenges encountered in developing single-page applications, and is intended to help developers build large, easily scalable and changing web apps. Starting with a project on Open Library API, you will be introduced to React and JSX before moving on to learning about the life cycle of a React component. In the second project, building a multi-step wizard form, you will learn about composite dynamic components and perform DOM actions. You will also learn about building a fast search engine by exploring server-side rendering in the third project on a search engine application. Next, you will build a simple frontpage for an e-commerce app in the fourth project by using data models and React add-ons. In the final project you will develop a complete social media tracker by using the flux way of defining React apps and know about the best practices and use cases with the help of ES6 and redux. By the end of this book, you will not only have a good understanding of ReactJS but will also have built your very own responsive frontend applications from scratch.

Who is this book for?

If you are a web developer and wish to learn ReactJS from scratch, then this book is tailor-made for you. Good understanding of Javascript, HTML, and CSS is expected.

What you will learn

  • Create, reuse, and compose React components using JSX
  • Share data between various React components and techniques for data flow within a React app
  • Handle user interactions with the help of event handlers and dynamic components
  • Set up and use various next generation ES2015/ES6 features with React
  • Understand the performance and immutability features of React using React add-ons
  • Learn the techniques of Animation in React
  • Use data stores to store model-related data and information
  • Create a flux-based React application by using Reflux library

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 21, 2016
Length: 280 pages
Edition : 1st
Language : English
ISBN-13 : 9781785282744
Vendor :
Facebook
Languages :
Tools :

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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Apr 21, 2016
Length: 280 pages
Edition : 1st
Language : English
ISBN-13 : 9781785282744
Vendor :
Facebook
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 87.98
ReactJS by Example - Building Modern Web Applications with React
$48.99
React Components
$38.99
Total $ 87.98 Stars icon
Banner background image

Table of Contents

14 Chapters
1. Getting Started with React Chevron down icon Chevron up icon
2. JSX in Depth Chevron down icon Chevron up icon
3. Data Flow and Life Cycle Events Chevron down icon Chevron up icon
4. Composite Dynamic Components and Forms Chevron down icon Chevron up icon
5. Mixins and the DOM Chevron down icon Chevron up icon
6. React on the Server Chevron down icon Chevron up icon
7. React Addons Chevron down icon Chevron up icon
8. Performance of React Apps Chevron down icon Chevron up icon
9. React Router and Data Models Chevron down icon Chevron up icon
10. Animation Chevron down icon Chevron up icon
11. React Tools Chevron down icon Chevron up icon
12. Flux Chevron down icon Chevron up icon
13. Redux and React Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.4
(9 Ratings)
5 star 22.2%
4 star 11.1%
3 star 11.1%
2 star 0%
1 star 55.6%
Filter icon Filter
Top Reviews

Filter reviews by




Mazahar May 03, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Nice book
Amazon Verified review Amazon
Amazon Customer May 10, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is one of the great book to kickstart on React. Provide the basics of React and bring you to next level of knowledge of modern web applications. I would strong recommend to read this book.
Amazon Verified review Amazon
MigoFast Aug 21, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I kind of figured after reading this book if I looked at the reviews folks would not like the 'pair programming' style - at first I thought it was a bit weird and novelty - but kept an open mind and actually found it somewhat natural and enjoyable and kind of a fun approachable way to read the 'same old' technical book.
Amazon Verified review Amazon
Armando Padilla Jun 05, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Great read so far. Love the authors approach to telling a story along with building a nice app. The book quickly ramps up and gets you going in building out a react application. So why 3 stars? Chapter 4 you will get lost. After page 65 there is no way to get the application running. The author does mentioned what files should be present and even the structure but nothing stating what should be in the required files to actually start the server. To get around this download the chapter 4 code from the book's site.
Amazon Verified review Amazon
hysterio Jul 21, 2016
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
The entire book is written as a conversation between two developers, one takes the role of the mentor (Mike) the other stands in for the reader as the learner (Shawn). However, nowhere does the book actually call out who is speaking and the character’s voices don’t differ enough to actually tell them apart just by reading what they are saying. This means you can’t devote your entire attention to learning React as you must track which developer is saying what to understand the situation.The conversation nature also makes it difficult to skim the text to find important pieces of information or steps in a process as these steps are hidden in dense conversational text. The book also frequently fails to clearly call out where the code is being used by providing a file path or file title anywhere in relation to the code. Meaning this book is pretty much worthless as a reference.
Amazon Verified review Amazon
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.