34,79 €
React.js is Facebook's dynamic frontend web development framework. It helps you build efficient, high-performing web applications with an intuitive user interface.
With more than 66 practical and self-contained tutorials, this book examines common pain points and best practices for building web applications with React. Each recipe addresses a specific problem and offers a proven solution with insights into how it works, so that you can modify the code and configuration files to suit your requirements.
The React Cookbook starts with recipes for installing and setting up the React.js environment with the Create React Apps tool. You’ll understand how to build web components, forms, animations, and handle events. You’ll then delve into Redux for state management and build amazing UI designs. With the help of practical solutions, this book will guide you in testing, debugging, and scaling your web applications, and get to grips with web technologies like WebPack, Node, and Firebase to develop web APIs and implement SSR capabilities in your apps. Before you wrap up, the recipes on React Native and React VR will assist you in exploring mobile development with React.
By the end of the book, you will have become familiar with all the essential tools and best practices required to build efficient solutions on the web with React.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 361
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Kunal ChaudhariAcquisition Editor: Larissa PintoContent Development Editor: Francis CarneiroTechnical Editor: Diksha WakodeCopy Editor: Safis EditingProject Coordinator: Alinka DiasProofreader: Safis EditingIndexer: Pratik ShirodkarGraphics: Jason MonteiroProduction Coordinator: Arvindkumar Gupta
First published: August 2018
Production reference: 1290818
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78398-072-7
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Carlos Santana Roldan is a senior web developer with more than 11 years of experience. Currently, he is working as a React Technical Lead in Disney ABC Television Group. He is the founder of Codejobs.com, one of the most popular developer communities in Latin America, training people in web technologies such as React, Node.js, and JavaScript.
Mayur Tanna is a senior IT consultant working with CIGNEX Datamatics. He has worked on various high-value projects with international clients such as World Bank and the United Nations and played a key role in creating the architecture of those projects using the latest technologies, including React, Angular, Node.js, MongoDB, Spring Boot, Firebase, Amazon Web Services, and Google Cloud Platform. Mayur is the co-author of the book Serverless Web Applications with React and Firebase. He holds a master's degree in Computer Applications and has trained lot of engineering students through tech workshops. In his free time, he plays table tennis and cricket.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
To the memory of my two grandmothers, Maria Concepción Carrillo, and Ana María Ochoa, to my mother, Thelma C. Roldán, and my father Francisco Santana, for their sacrifices and for exemplifying the power of determination and dedication.
Title Page
Copyright and Credits
React Cookbook
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Dedication
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Get in touch
Reviews
Working with React
Introduction
Working with the latest JS features in React
How to do it...
What's new in React?
How to do it...
Using React on Windows
How to do it...
Conquering Components and JSX
Introduction
Creating our first React component
Getting ready
How to do it...
How it works...
There's more...
Organizing our React application
How to do it...
How it works...
Styling a component with CSS classes and inline styles
How to do it...
How it works...
There's more...
Passing props to a component and validating them with PropTypes
How to do it...
How it works...
There's more...
Using local state in a component
How to do it...
How it works...
There's more...
Making a functional or stateless component
How to do it...
How it works...
There's more...
Understanding React lifecycle methods
How to do it...
Todo list – implementing ComponentWillMount
Pomodoro timer – implementing the constructor and componentDidMount
Crypto coins exchanger – implementing shouldComponentUpdate
Notes – implementing componentWillReceiveProps and componentWillUnmount
C3.js chart – implementing componentDidUpdate
Basic animation – implementing componentWillUpdate
How it works...
Understanding React Pure Components
Getting ready
How to do it…
How it works…
Preventing XSS vulnerabilities in React
How to do it...
How it works...
There's more...
Handling Events, Binding and Useful React Packages
Introduction
Binding methods using the constructor versus using arrow functions
How to do it...
How it works...
Creating form elements with events
How to do it...
How it works...
There's more...
Displaying information in a modal with react-popup
Getting ready
How to do it...
How it works...
There's more...
Implementing Airbnb React/JSX Style Guide
Getting ready
How to do it...
How it works...
There's more...
Updating our title and meta tags with React Helmet
Getting ready
How to do it...
How it works...
There's more...
Adding Routes to Our Application with React Router
Introduction
Implementing React Router v4
Getting ready
How to do it...
How it works...
There's more...
Adding parameters to our routes
How to do it...
How it works...
Mastering Redux
Introduction
Creating a Redux Store
Getting ready
How to do it...
How it works...
Making action creators and dispatching actions
Getting ready
How to do it...
How it works...
Implementing Firebase with Redux
Getting ready
How to do it...
How it works...
Creating Forms with Redux Form
Introduction
Creating a controlled form with the local state
Getting ready
How to do it...
How it works...
Building a form using Redux Form
Getting ready
How to do it...
How it works...
Implementing validation in a form
How to do it...
How it works...
Animations with React
Introduction
Animating a todo list with ReactCSSTransitionGroup
Getting Ready
How to do it...
How it works...
Using react-animations library
Getting ready
How to do it...
There's more...
Creating our first animation with React Pose
Getting ready
How to do it...
How it works...
There's more...
Creating an API with Node.js Using MongoDB and MySQL
Introduction
Creating a basic API with Express
Getting ready
How to do it...
How it works...
Building a database with MongoDB
Getting ready
Installing MongoDB Community Edition manually (the hard way)
Installing MongoDB Community Edition with Homebrew (the easy way)
Running MongoDB
How to do it...
How it works...
GET method endpoints
POST method endpoints
DELETE method endpoints
PUT method endpoints
Building a database with MySQL
Getting ready
How to do it...
How it works...
POST method endpoints
GET method endpoints
DELETE method endpoints
PUT method endpoints
Adding access tokens to secure our API
Getting ready
How to do it...
How it works...
There's more...
Apollo and GraphQL
Introduction
Creating our first GraphQL server
Getting ready
How to do it...
How it works...
There's more...
Creating a Twitter timeline with Apollo and GraphQL
Getting ready
Creating our GraphQL backend server
How to do it...
How it works...
Mastering Webpack 4.x
Introduction
Webpack 4 Zero Configuration
Getting Ready
How to do it...
How it works...
There's more...
Adding React to Webpack 4
Getting Ready
How to do it...
How it works...
There's more...
Adding Webpack Dev Server and Sass, Stylus, or LessCSS with React
Getting Ready
How to do it...
How it works...
There's more...
Webpack 4 Optimization – Splitting Bundles
Getting Ready
How to do it...
How it works...
Implementing Node.js with React/Redux and Webpack 4
Getting Ready
How to do it...
How it works...
There's more...
Implementing Server-Side Rendering
Introduction
Implementing Server-Side Rendering
Getting ready
How to do it...
How it works...
There's more...
Implementing promises with Server-Side Rendering
Getting ready
How to do it...
How it works...
Implementing Next.js
Getting ready
How to do it...
How it works...
Testing and Debugging
Introduction
Testing our first component with Jest and Enzyme
Getting ready
How to do it...
How it works...
There's more...
Testing a Redux Container, Actions, and Reducers
Getting Ready
How to do it...
Debugging a React application using React and Redux Dev Tools
Getting Ready
How to do it...
Simulating Events
How to do it...
How it works...
Deploying to Production
Introduction
Deploying to production on Digital Ocean
Getting ready
How to do it...
How it works...
There's more...
Configuring Nginx, PM2, and a domain in our Droplet
Getting Ready
How to do it...
How it works...
There's more...
Implementing Jenkins (continuous integration)
Getting Ready
How to do it...
How it works...
Working with React Native
Introduction
Creating our first React Native Application
Getting Ready
How to do it...
How it works...
Creating a Todo List with React Native
How to do it...
How it works...
There's more...
Implementing React Navigation V2
Getting Ready
How to do it...
How it works...
Most Common React Interview Questions
Other Books You May Enjoy
Leave a review - let other readers know what you think
Nowadays exists tons of JavaScript libraries, frameworks, and tools for Web development. However, we should evaluate each technology to see if it fits for our project requirements. That's why I want to introduce to you React, one of the most powerful libraries to create dynamic UIs. Right now is the most popular library (not a framework) made by Facebook. I have worked with others JS frameworks such as AngularJS (also the new versions Angular 2, 4, 5), Backbone.js, Ember, and Vue.js in different projects but I can tell you that using React I enjoy more to developing new Web applications.
React has changed the way of doing Web applications and combined with Redux, we get a powerful frontend architecture that makes sense not only to experienced developers but also to those who're just starting their frontend journey.
The book introduces all the tools and best practices of React in simple recipes easy to follow, all of the recipes in this book are 100% practical and each one has the necessary code to understand all the important things.
Welcome to a better future and have fun reading and learning from this book.
The book can be used by any developer who has a basic knowledge of building web applications. Mainly for JavaScript developers but not limited to any other type of devs.
Chapter 1, Working with React, React is a JavaScript library (MIT License) made by Facebook to create interactive UIs. It's used to create dynamic and reusable components. The most powerful thing about React is that can be used in the client, server, mobile applications and even VR applications.
Chapter 2, Conquering Components and JSX, this chapter contains recipes related to how to create components in React. We are going to learn how to create React components (class components, pure components, and functional components) and organize our project structure.
Chapter 3, Handling Events, Binding and Useful React Packages, this chapter contains recipes related to handling events, binding methods in React and we will implement some of the most useful React packages.
Chapter 4, Adding Routes to Our Application with React Router, in this chapter, we are going to learn how to add dynamic routes in our project using React Router v4.
Chapter 5, Mastering Redux, Redux is a predictable state container for JavaScript apps. That means Redux can be used with vanilla JavaScript or frameworks/libraries such as Angular and jQuery. Redux is mainly a library responsible for issuing state updates and responses to actions.
Chapter 6, Creating Forms with Redux Form, Forms are a fundamental part of any web application, and in the following recipes, we are going to learn how to use forms with and without Redux Form.
Chapter 7, Animations with React, Animations are very common in any web application. Since CSS3, animations have become widespread and easy to implement. The most common use of animations are transitions, where you can change CSS properties and define the duration or delay.
Chapter 8, Creating an API with Node.js Using MongoDB and MySQL, Node.js is widely used as a backend for web applications because it is easy to create an API and its performance is better than technologies such as Java, PHP, and Ruby. Usually, the most popular way to use Node.js is by using a framework called Express.
Chapter 9, Apollo and GraphQL, GraphQL is an Application Layer Query Language which can be used with any database, also is an open source (MIT license) created by Facebook. The main difference with REST is that GraphQL does not use endpoints but queries instead and is supported by most of the server languages such as JavaScript (Node.js), Go, Ruby, PHP, Java, Python, and so on.
Chapter 10, Mastering Webpack 4.x, Webpack 4 does not need a configuration file by default. Before in the oldest versions, you must have a configuration file, but of course, if you need to customize Webpack 4 to your project needs, you can still create a configuration file which will be way easier to configure.
Chapter 11, Implementing Server-Side Rendering, Probably you don't need to worry about Server Side Rendering (SSR) if you don't care too much about SEO. Currently, the Googlebot supports Client Side Rendering (CSR), and it can index our site in Google, but if you care about SEO and you are worried about improving the SEO on others Search Engines like Yahoo, Bing or DuckDuckGo then using Server Side Rendering (SSR) is the way to go.
Chapter 12, Testing and Debugging, testing and debugging are very important for any project that wants to have the best quality. Unfortunately, many developers do not care about testing (unit tests) because they think that will reduce the speed of the development and some of them leave it until the end of the project. In my personal experience, I can say that testing since the beginning of the project will save you time because at the end you will have fewer bugs to fix.
Chapter 13, Deploying to Production, now is time to deploy our application to production and show it to the world. In this chapter, you will learn how to deploy our React Application using one of the best cloud services: Digital Ocean.
Chapter 14, Working with React Native, React Native is a framework for building mobile apps using JavaScript and React. Many people think that with React Native you make some "mobile web app" or a "hybrid app" (like Ionic, PhoneGap or Sencha) but you build a native app because React Native converts your React code to Java for Android and Objective-C for iOS apps.
To master React, you need to have a fundamental knowledge of JavaScript and Node.js. The book mostly targets Web developers, and at the time of writing, the following assumptions were made for the reader:
The reader knows how to install the latest version of Node.js.
An intermediate developer who can understand JavaScript ES6 syntax.
Little experience with CLI tools and Node.js syntax.
The book also has a little for Mobile developers (iOS and Android) using React Native, if you are a beginner you should learn how to install Android SDK or the iOS simulator with Xcode.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/React-Cookbook. If there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
In this chapter, the following recipes will be covered:
Introduction
Working with the latest JS features in React
What's new in React?
Using React on Windows
React is a JavaScript library (MIT License) made by Facebook to create interactive UIs. It's used to create dynamic and reusable components. The most powerful thing about React is that can be used in the client, server, mobile applications, and even VR applications.
In the modern web, we need to manipulate the DOM constantly; the problem is that doing this a lot may affect the performance of our application seriously. React uses a Virtual DOM, which means that all updates occur in memory (this is faster than manipulating the real DOM directly). The learning curve of React is short in comparison with other JavaScript frameworks such as Angular, Vue, or Backbone, mainly because the React code is mostly written with modern JavaScript (classes, arrow functions, string templates, and so on) and does not have too many patterns used to write code, like Dependency Injection, or a template system, like in Angular.
Companies such as Airbnb, Microsoft, Netflix, Disney, Dropbox, Twitter, PayPal, Salesforce, Tesla, and Uber are extensively using React in their projects. In this book, you will learn how to develop your React applications in the way they do, using best practices.
As I said in the introduction, React is mainly written with modern JavaScript (ES6, ES7, and ES8). If you want to take advantage of React, there are some modern JS features that you should master to get the best results for your React applications. In this first recipe, we are going to cover the essential JS features so you are ready and can start working on your first React application.
This paragraph was written on August 14, 2018, and the latest version of React was 16.4.2. The React 16 version has a new core architecture named Fiber.
In this recipe, we will see the most important updates in this version that you should be aware of to get the most out of React.
I'm not a big fan of Windows for development since it's kind of problematic to configure sometimes. I will always prefer Linux or Mac, but I'm aware that a lot of people who are reading this book will use Windows. In this recipe, I'll show you the most common problems you may have when you try to follow the recipes in this book using Windows.
We'll now see the most common problems using Windows for development:
Terminal
: The first problem you will face is to use the Windows terminal (CMD) because it does not support Unix commands (like Linux or Mac). The solution is to install a Unix Terminal; the most highly recommended is to use the
Git Bash
Terminal, which is included with
Git
when you install it (
https://git-scm.com
), and the second option is to install
Cygwin
, which is a Linux Terminal in Windows (
https://www.cygwin.com
).
Environment variables
: Another common problem using Windows is to set environment variables. Generally, when we write npm scripts, we set environment variables such as
NODE_ENV=production
or
BABEL_ENV=development
, but to set those variables in Windows, you use the
SET
command, which means you need to do
SET NODE_ENV=production
or
SET BABEL_ENV=development
. The problem with this is that if you are working with other people that use Linux or Mac, they will have problems with the
SET
command, and probably you will need to ignore this file and modify it only for your local environment. This can be tedious. The solution to this problem is to use a package called cross-env; you can install it by doing
npm install cross-env
, and this will work in Windows, Mac, and Linux:
"
scripts
": { "
start
": "
cross-env
NODE_ENV=development webpack-dev-server -- mode development --open", "
start-production
": "
cross-env
NODE_ENV=production webpack-dev- server --mode production" }
Case-sensitive files or directories
: In reality, this also happens on Linux, but sometimes it is very difficult to identify this problem, for example, if you create a component in the
components/
home
/Home.jsx
directory but in your code you're trying to import the component like this:
import
Home
from
'./components/
Home
/Home';
Paths
: Windows uses a backslash (
\
) to define a path, while in Mac or Linux they use a forward slash (
/
). This is problematic because sometimes we need to define a path (in Node.js mostly) and we need to do something like this:
// In Mac or Linux
app.
use
( stylus.
middleware
({
src
:
__dirname
+ '
/
stylus',
dest
:
__dirname
+ '
/
public
/
css',
compile
: (str, path) => {
return
stylus(str) .
set
('filename', path) .
set
('compress', true); } }) );
// In Windows
app.
use
( stylus.
middleware
({
src
:
__dirname
+ '
\
stylus',
dest
:
__dirname
+ '
\
public
\
css',
compile
: (str, path) => {
return
stylus(str) .
set
('filename', path) .
set
('compress', true); } }) );
// This can be fixed by using path
import
path
from
'path';
// path.join will generate a valid path for Windows or Linux and Mac
app.
use
( stylus.
middleware
({
src
: path.
join
(
__dirname
, 'stylus'),
dest
: path.
join
(
__dirname
, 'public', 'css'),
compile
: (str, path) => {
return
stylus(str) .
set
('filename', path) .
set
('compress', config().html.css.compress); } }) );
In this chapter, the following recipes will be covered:
Creating our first React component
Organizing our React application
Styling a component with CSS classes and inline styles
Passing props to a component and validating them with PropTypes
Using local state in a component
Making a functional or stateless component
Understanding React lifecycle methods
Understanding React Pure Components
Preventing XSS vulnerabilities in React
This chapter contains recipes related to how to create components in React. We are going to learn how to create React components (class components, pure components, and functional components) and organize our project structure. We'll also learn how to use React local state, implement all the React lifecycle methods, and finally, we'll see how to prevent XSS vulnerabilities.
The component is the essential part of React. With React you can build interactive and reusable components. In this recipe, you will create your first React component.
First, we need to create our React application using create-react-app. Once that is done, you can proceed to create your first React component.
Before you install create-react-app, remember that you need to download and install Node from www.nodejs.org. You can install it for Mac, Linux, and Windows.
Install create-react-app globally by typing this command in your Terminal:
npm install
-g create-react-app
Or you can use a shortcut:
npm i -g create-react-app
Let's build our first React application by following these steps:
Create our React application with the following command:
create-react-app my-first-react-app
Go to the new application with
cd my-first-react-app
and start it with
npm start
.
The
application should now be running at
http://localhost:3000
.
Create a new file called
Home.js
inside your
src
folder
:
import
React, { Component }
from
'react';
class
Home
extends
Component {
render
() {
return
<h1>I'm Home Component</h1>; }}
export default
Home;
You may have noticed that we are exporting our class component at the end of the file, but it's fine to export it directly on the class declaration, like this:
import
React, { Component }
from
'react';
export default class
Home
extends
Component {
render
() {
return
<h1>
I'm Home Component
</h1>
; } }
Now that we have created the first component, we need to render it. So we need to open the
App.js
file, import the
Home
component, and then add it to the render method of the
App
component. If we are opening this file for the first time, we will probably see a code like this:
import
React, { Component }
from
'react';
import
logo
from
'./logo.svg';
import
'./App.css';
class
App
extends
Component {
render
() {
return
( <div
className
="App"> <header
className
="App-header"> <img src={logo}
className
="App-logo" alt="logo" /> <h1
className
="App-title">Welcome to React</h1> </header> <p
className
="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } }
export default
App;
Let's change this code a little bit. As I said before, we need to import our
Home