ReactJS Blueprints - Sven A. Robbestad - E-Book

ReactJS Blueprints E-Book

Sven A. Robbestad

0,0
38,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Create powerful applications with ReactJS, the most popular platform for web developers today

About This Book

  • Create web apps with the most popular JavaScript library in the world
  • Learn how to speed up your development process and save valuable time
  • Work though step-by-step tutorials that provide easy-to-understand solutions to real-world problems

Who This Book Is For

This book is for those who want to develop applications with ReactJS. With its wide variety of topics, it caters both to the inexperienced developer as well as to the advanced, and it doesn't require any prior experience with ReactJS.

What You Will Learn

  • Create a development environment that speeds up your development process
  • Find out about responsive web development and create apps that can be used on any device
  • Effortlessly connect to public and private APIs
  • Create efficient components that are easily testable and small enough to completely understand
  • Understand what data flow means in ReactJS and why you never need to worry about where data changes originate
  • Create universal apps that run on the browser as well as on the server
  • Work with modern front-end tooling and level up your skills
  • Train yourself to think in terms of ReactJS

In Detail

The JavaScript revolution has landed! ReactJS is one of those rare technologies that comes out of nowhere and turns established practices on their head. It provides a different way of thinking about how you should develop your apps, and has already gained a massive adoption among web developers. Join the revolution, build web apps faster, and have more fun developing!

Packed with real-world code, this book starts by covering the idea behind ReactJS and the key concepts you must familiarize yourself with. You will learn how to bootstrap your ReactJS projects and you'll also be provided with a handy scaffolding that you can use and reuse over and over.

We then go on to cover a wide variety of apps, and will help you to structure and build your own components. Next, you will build a web shop, create a fully responsive and routable app, and also develop a real-time search app. Further on, you will be taught to work with public APIs to create a map-based application. You will also be taken through some advanced concepts such as Redux that are making a huge splash currently in the world of ReactJS. You'll learn how to efficiently seal off your app for guest access, interact with hardware APIs, and create a photo app. You will then master the art of making your apps universal, and find out how to deploy them to the cloud. Finally, we wrap up the book as you are shown how to make a game. What better way to kick off your ReactJS development journey?

Style and approach

This is an easy-to-follow guide full of real-world ReactJS applications. Each chapter is self-contained, and every code example is explained in detail.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 390

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

ReactJS Blueprints
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Diving Headfirst into ReactJS
Introducing ReactJS
Modern JavaScript development
Component specification
Props and states
Props
States
render
statics
propTypes
displayName
Life cycle methods
componentDidMount
componentWillMount
shouldComponentUpdate
componentWillReceiveProps
componentWillUpdate
componentDidUpdate
componentWillUnmount
Synthetic events and the Virtual DOM
The DOM
The virtual DOM
Synthetic event handlers
Putting it all together
Composition
Developing with modern frontend tools
Browserify
Scaffolding our React app
Running the app
Summary
2. Creating a Web Shop
An overview of the components
Setting up a shop
Creating the layout
Adding your own CSS code
Adding a route handler
The menu and footer
Creating the pages
Creating a database of products
Creating a data store to fetch the products
Building the product's listing and the item page
Creating a cart store
Checking out
Providing a receipt
Summary
3. Responsive Web Development with ReactJS
Creating a flexible layout
Choosing the right framework
Setting up your app with Bootstrap
Creating a flexible grid
Creating a responsive menu and navigation bar
Creating responsive wells
Creating responsive panels
Creating responsive alerts
Responsively embedded media and video content
Creating responsive buttons
Creating dynamic progress bars
Creating fluid carousels
Working with fluid images and the picture element
Reducing your footprint
Creating a Reactified picture element
Creating responsive form fields
Using Glyphicons and font-awesome icons
Creating a responsive landing page
Summary
4. Building a Real-Time Search App
Creating your own search API
Getting started with your API
Creating the API
Importing documents
Querying the API
Creating a wildcard search
Securing your API
Creating your ReactJS search app
Setting up your app
Creating a search service
Testing the service
Setting up the store
Creating the search view
Performing searches
Navigating the search results with the arrow keys
Debouncing the search
Moving beyond the quick search to the results page
Setting up the results page
Setting up pagination
Setting up endless scroll
Summary
5. Creating a Map App with HTML5 APIs
The state of HTML5 APIs
The High Resolution Time API
The Vibration API
The Battery Status API
The Page Visibility API
The Geolocation API
Creating our map app
Setting up geolocation
Showing static maps
Creating an interactive map
Summary
6. Advanced React
A new bundling strategy
How Browserify works
How Webpack works
A difficult choice – Browserify or Webpack
Creating a new scaffold with Webpack
The Babel configuration
The Webpack configuration
Adding assets
Creating an Express server
Adding ReactJS to the mix
Starting the server
Introducing Redux
The global store
Understanding actions
Understanding reducers
Installing Redux
Creating a login app
Creating an action
Creating a reducer
Creating a store
Adding devtools
Tying the files together
Handling refresh
The Login API
Summary
7. Reactagram
Getting started
Setting up the routes
Creating a higher order function
Creating a random username
Creating a welcome screen
Taking a picture
Adding filters
Adding the stream
Creating an item page and adding comments
Wrapping up
Summary
8. Deploying Your App to the Cloud
Choosing a cloud provider
Setting up cloud deployment with npm
Preparing your Browserify app for cloud deployment
The actual process
Deploying a Webpack app to the cloud
Summary
9. Creating a Shared App
Server rendering versus client rendering
Terminology confusion
Developing a server-rendered app
Adding packages
Adding CSS
Adding Bootstrap CDN to index.html
Creating components
Setting up a server-rendered Express React server
Setting up Webpack for server-rendering
Setting up npm scripts for server rendering
Adding Redux to your server-rendered app
Adding packages
Adding files
Adding server rendering
Performing faster cloud deployment
The final structure
Summary
10. Making a Game
The optimal Webpack configuration
Scripting with ShellJS
Static typechecking with Flow
Creating an HTML5 canvas engine
Creating the game
Responding to keyboard events
Further improvements
Summary
Index

ReactJS Blueprints

ReactJS Blueprints

Copyright © 2016 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

First published: July 2016

Production reference: 1250716

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-654-6

www.packtpub.com

Credits

Author

Sven A. Robbestad

Reviewers

Michele Bertoli

Tassinari Olivier

Acquisition Editor

Reshma Raman

Content Development Editor

Merwyn D'souza

Sachin Karnani

Technical Editor

Abhishek R. Kotian

Copy Editor

Gladson Monteiro

Project Coordinator

Nikhil Nair

Ritika Manoj

Proofreader

Safis Editing

Indexer

Rekha Nair

Graphics

Kirk D'Penha

Production Coordinator

Melwyn Dsa

Cover Work

Melwyn Dsa

Foreword

Sven has spent many months writing ReactJS Blueprints, and it shows. This book is a great way to get up and running with ReactJS quickly and to understand the best way to architect applications with ReactJS.

One of the best parts about Sven's writing is how pragmatic the examples are. Each concept is tied together with the next through the judicious use of real-world, relatable examples, and each concept is explained in detail as it's introduced.

Today, frontend developers are facing increasing JavaScript fatigue and an overwhelming number of competing frameworks, libraries, and build tools. ReactJS Blueprints can serve as your roadmap for navigating this vibrant—and daunting—ecosystem with clarity and ease.

Once you've completed ReactJS Blueprints, you'll be in the perfect position to begin a new ReactJS app or bring ReactJS into your existing system. This book is truly a one-stop-shop for ReactJS and modern web application architecture in general, and it is a lot of fun to read too!

Pete Hunt

CEO at Smyte, member of the original React.js team at Facebook

About the Author

Sven A. Robbestad is a developer with a keen interest in the Web and the languages you use for developing for the Web. He started programming at a young age, beginning with C on the Commodore Amiga. He made the Web his career in the early 90s. His favorite programming language is JavaScript, but he likes to work with an assortment of languages, such as Python, PHP, and Java, to mention a few. In his spare time, he loves engaging with fellow programmers, traveling, and speaking at conferences.

I would like to thank my wife, Monica, and my children, Ida Alana and Henry Alexander, for their patience. I know that living with a developer is challenging and even more so when he's writing a book. I would also like to thank Packt Publishing for giving me this opportunity, and the editorial team, especially Merwyn and Reshma. It's been a joy.

About the Reviewers

Michele Bertoli is a frontend developer with a passion for beautiful UIs.

Born in Italy, he moved to London with his family to look for new exciting job opportunities. He has a degree in computer science, and he loves clean and well-tested code. Currently, he is working at YPlan, crafting modern JavaScript applications with React.js. He is a big fan of open source and is always trying to learn something new.

I would like to thank my wife and my son for making my days better with their smiles and the WEBdeBS community, which helped me to move forward in my career.

Tassinari Olivier is a curious and persevering person who has always loved discovering new technologies. His passion for building things started at a very young age, and he began to launch websites 8 years ago while studying maths, physics, and computer sciences. He was involved in the development of Material UI at a very early stage and became one of the top committers. Though he is currently working as a frontend engineer at Doctolib, a company streamlining access to healthcare, he spends a lot of time contributing to the open source community.

I would line to thank Reshma Raman for reaching me and providing me with the opportunity to review my first book. I would also like to thank my family for their support.

www.PacktPub.com

eBooks, discount offers, and more

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.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

ReactJS was developed as a tool to solve a problem with the application state, but it quickly grew to become the dominant library for web development. It became popular because it threw away the HTML-centric way of developing web apps for JavaScript, which proved to be a remarkably developer-friendly way to develop web apps. With the help of this book, discover how you can take advantage of ReactJS to create web apps that are fun to code and easy to understand.

What this book covers

Chapter 1, Diving Headfirst into ReactJS, introduces you to the ReactJS library, teaches you how to structure your code, and introduces modular components.

Chapter 2, Create a Web Shop, walks you through the building of a web shop, from front page to checkout, and explains the unidirectional data flow pattern.

Chapter 3, Responsive Web Development with ReactJS, teaches you how to develop responsive apps with ReactJS and gives instructions on how to build a basic responsive app.

Chapter 4, Building a Real-Time Search App, walks you through the construction of an application that accepts input and returns data from an API.

Chapter 5, Creating a Map App with HTML5 APIs, teaches you how to access HTML5 APIs while building a map application.

Chapter 6, Advanced React, demonstrates how to transition to JavaScript 2015 classes, implements Redux, and walks you through a login application.

Chapter 7, Reactagram, walks you through building an Instagram-like application with Firebase as the backend.

Chapter 8, Deploying Your App to the Cloud, covers Cloud strategies and guides you to make production-ready deploys of your apps.

Chapter 9, Creating a Shared App, covers how to create a fully isomorphic app, and walks you through a blueprint for server-side rendering with Redux.

Chapter 10, Making a Game, walks you through the building of a game engine and game in ReactJS.

What you need for this book

Developing web apps doesn't require any special equipment. You need a computer (Windows, Linux, or Mac), a code editor (any will do), an Internet connection, and a console application.

Who this book is for

This book is for those who want to develop applications with ReactJS. With its wide variety of topics, it caters to both inexperienced developers as well as advanced developers, and it doesn't require any prior experience with ReactJS.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

<Button bsSize="medium" onClick={CartActions.AddToCart.bind(null, this.props.productData)}> Add to cart </Button>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

getInitialState() { return { results: [], resultsToShow: 10, numResults: 0, threshold: -60, increase: 3, showResults: true } },

Any command-line input or output is written as follows:

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "The connection to the payment API should be hooked up to the Proceed to checkout button."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

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.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/reactjsblueprints. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Diving Headfirst into ReactJS

Welcome dear reader! In this book, you'll find a set of blueprints that you can use to develop modern web apps with ReactJS.

This chapter will introduce you to ReactJS and cover how to work with a component-based architecture. You will learn all the important concepts in ReactJS, such as creating and mounting components, working with props and states, understanding the life cycle methods, and setting up a development workflow for efficient development.

In this chapter we will:

Introduce ReactJSExplore the props and statesLearn all about the important life cycle methodsWalk through synthetic events and the virtual DOMLearn the modern JavaScript developer's workflowCompositionCreate a basic scaffolding for all our apps

Even if you have previous experience with ReactJS, it's worth reading through this chapter, especially the scaffolding part, as we'll be using this scaffold for the majority of the blueprints in this book.

Let's begin!

Introducing ReactJS

To efficiently develop with ReactJS, it is vital to understand what it is and is not. ReactJS is not a framework. ReactJS describes itself as the V in the MVC (Model-View-Controller) design pattern. It's a view library that you can combine with frameworks such as AngularJS, Ember, and Meteor or even in conjunction with other popular JavaScript libraries, such as Knockout.

Many people use React on its own and combine it with a data flow pattern called Flux. The idea behind Flux is to establish unidirectional data flow, meaning that data should originate at a single point in your app and flow downwards. We'll look more closely into this pattern in Chapter 2, Creating a Web Shop.

Modern JavaScript development

In 2015, JavaScript got its first major upgrade in many years. The syntax is JavaScript 2015. You may know it as EcmaScript 6. The EcmaScript committee decided on a name change in mid-2015, and from now on, JavaScript is going to be updated yearly. Modern browsers are slowly implementing support for the new features.

Note

A note on the code you'll be seeing in this book. We will be using JavaScript 2015 throughout the book. Evergreen browsers such as Firefox, Chrome, and Microsoft Edge will implement the new functionality on their own timeline, which means that some browsers may support new features before others, while some features may not be implemented at all.

You will most likely find yourself in a situation where you'd like to take advantage of new language features without wanting to wait for it to be implemented. Backwards compatibility is also an issue because you don't want to leave your users behind.

The solution to both of these concerns is to use a transpiler to generate a baseline EcmaScript-5-compatible code, such as Traceur or Babel. Since Babel was partly built with ReactJS in mind, I suggest that you go with this one, and throughout the book, we'll be depending on Babel for our transpiling needs.

We'll be exploring the modern developer's workflow in this book by developing and iterating a scaffolding or a basic setup that we can use when starting new projects. When setting up and using this scaffolding, we'll rely heavily on the terminal, Node.js and npm. Don't worry if this is unfamiliar ground for you. We'll go slow.

Life cycle methods

Life cycle methods are a set of functions that you can override in your component. Initially, all but shouldComponentUpdate (which defaults to true) is empty.

componentDidMount

This is one of the most common methods you'll employ in your apps. Here's where you place any functions you want to run directly after the component has been rendered for the first time.

You have access to the current contents of states and props in this method, but take care to never run setState in here, as that will trigger an endless update loop.

It's worth noting that if you're making a server-side app, this component will not be called. In this case, you'll have to rely on componentWillMount instead:

componentDidMount() { // Executed after the component is mounted }

componentWillMount

This method will be executed before the component is rendered for the first time. You have access to the current component's state and props here, and unlike componentDidMount, it's safe to run setState here (ReactJS will understand that state changes in this method should be set immediately and not trigger a re-render).

This method is executed on both server-side and client-side apps:

componentWillMount() { // Executed before the component is mounted }

shouldComponentUpdate

This method is invoked whenever the component receives new props or a change in state occurs.

By default, shouldComponentUpdate returns a true value. If you override it and return false, the component will never be updated despite receiving updated props or a new state. This can be useful if you create a component that should only be updated if certain conditions are met or if it should never be updated at all. You can benefit from speed increases if you set this to false when you have a component that should never be updated. However, you should take great care when using this method because careless use can lead to bugs that can be very hard to track down.

componentWillReceiveProps

This method lets you compare the incoming props and can be used as an opportunity to react to a prop transition before the render method is called. Invoke this method with componentWillReceiveProps(object nextProps) in order to access the incoming props with nextProps.

It's worth noting that if you call setState here, an additional re-render will not be triggered. It's not called for the initial render.

There's no analogous method to react to a pure state change, but you can use componentWillUpdate if you need a way to react to state changes before they are rendered.

This method is not executed on the initial render:

componentWillReceiveProps(nextProps) { // you can compare nextProps with this.props // and optionally set a new state or execute functions // based on the new props }

componentWillUpdate

This method is executed before the rendering, when the component receives new props or states but not on the initial render.

Invoke this method with componentWillUpdate(object nextProps, object nextState) in order to access the incoming props and states with nextProps and nextState.

Since you can evaluate a new state in this method, calling setState here will trigger an endless loop. This means that you cannot use setState in this method. If you want to run setState based on a prop change, use componentWillReceiveProps instead:

componentWillUpdate (nextProps) { // you can compare nextProps with this.props // or nextState with this.state }

componentDidUpdate

This method is executed whenever the component receives new props or states and the render method has been executed:

componentDidUpdate() { // Execute functions after the component has been updated }

componentWillUnmount

The final life cycle method is componentWillUnmount. This is invoked just before the component is unmounted from the DOM. If you need to clean up memory or invalidate timers, this is the place to do it:

componentWillUnmount() { // Execute functions before the component is unmounted // from the DOM }

Summary