39,59 €
Facebook's React combined with industry-tested, server-side technologies, such as Node, Express, and MongoDB, enables you to develop and deploy robust real-world full-stack web apps. This updated second edition focuses on the latest versions and conventions of the technologies in this stack, along with their new features such as Hooks in React and async/await in JavaScript. The book also explores advanced topics such as implementing real-time bidding, a web-based classroom app, and data visualization in an expense tracking app.
Full-Stack React Projects will take you through the process of preparing the development environment for MERN stack-based web development, creating a basic skeleton app, and extending it to build six different web apps. You’ll build apps for social media, classrooms, media streaming, online marketplaces with real-time bidding, and web-based games with virtual reality features. Throughout the book, you’ll learn how MERN stack web development works, extend its capabilities for complex features, and gain actionable insights into creating MERN-based apps, along with exploring industry best practices to meet the ever-increasing demands of the real world.
By the end of this React book, you’ll be able to build production-ready MERN full-stack apps using advanced tools and techniques in modern web development.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 777
Veröffentlichungsjahr: 2020
Copyright © 2020 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.
Acquisition Editor:Clint RodricksContent Development Editor:Aamir AhmedSenior Editor: Hayden EdwardsTechnical Editor:Deepesh PatelCopy Editor:Safis EditingProject Coordinator: Kinjal BariProofreader: Safis EditingIndexer:Manju ArasanProduction Designer:Joshua Misquitta
First published: May 2018 Second edition: April 2020
Production reference: 1160420
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-83921-541-4
www.packt.com
To my parents, for setting examples of perseverance and relentless dedication.
-Shama Hoque
Packt.com
Subscribe to our online digital library for full access to over 7,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
Fully searchable for easy access to vital information
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.packt.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.packt.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.
Shama Hoque has more than 9 years of experience as a software developer and mentor, with a master's in software engineering from Carnegie Mellon University.
From Java programming to full-stack development with JavaScript, the applications she has worked on include national Olympiad registration websites, universally accessible widgets, video conferencing apps, and 3D medical reconstruction software.
Currently, she makes web-based prototypes for R&D start-ups in California, while training aspiring software engineers and teaching web development to CS undergrads in Bangladesh.
Kirill Ezhemenskii is an experienced software engineer, frontend and mobile developer, solution architect, and the CTO of a healthcare company. He is also a functional programming advocate; an expert in the React stack, GraphQL, and TypeScript; and a React Native mentor.
Carlos Santana Roldán is a senior web developer with more than 12 years of experience. Currently, he is working as a senior React developer at MindBody Inc. He is the founder of Dev Education, one of the most popular developer communities in Latin America, training people in web technologies such as React, Node.js, GraphQL, and JavaScript in general.
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.
Title Page
Copyright and Credits
Full-Stack React Projects Second Edition
Dedication
About Packt
Why subscribe?
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Getting Started with MERN
Unleashing React Applications with MERN
What is new in the second edition?
Book structure
Getting started with MERN
Building MERN applications from the ground up
Developing web applications with MERN
Advancing to complex MERN applications
Going forward with MERN
Getting the most out of this book
The MERN stack
Node
Express
MongoDB
React
Relevance of MERN
Consistency across the technology stack
Takes less time to learn, develop, deploy, and extend
Widely adopted in the industry
Community support and growth
Range of MERN applications
MERN applications developed in this book
Social media platform
Web-based classroom application
Online marketplace
Expense tracking application
Media streaming application
VR game for the web
Summary
Preparing the Development Environment
Selecting development tools
Workspace options
Local and cloud development
IDE or text editors
Chrome Developer Tools
Git
Installation
Remote Git hosting services
Setting up MERN stack technologies
MongoDB
Installation
Running the mongo shell
Node.js
Installation
Node version management with nvm
Yarn package manager
Modules for MERN
Key modules
devDependency modules
Checking your development setup
Initializing package.json and installing Node.js modules
Configuring Babel, Webpack, and Nodemon
Babel
Webpack
Client-side Webpack configuration for development
Server-side Webpack configuration
Client-side Webpack configuration for production
Nodemon
Frontend views with React
Server with Express and Node
Express app
Bundling React app during development
Serving static files from the dist folder
Rendering templates at the root
Connecting the server to MongoDB
Run scripts
Developing and debugging in real time
Summary
Building MERN from the Ground Up
Building a Backend with MongoDB, Express, and Node
Overview of the skeleton application
Feature breakdown
Defining the backend components
User model
API endpoints for user CRUD
Auth with JSON Web Tokens
How JWT works
Setting up the skeleton backend
Folder and file structure
Initializing the project
Adding package.json
Development dependencies
Babel
Webpack
Nodemon
Config variables
Running scripts
Preparing the server
Configuring Express
Starting the server
Setting up Mongoose and connecting to MongoDB
Serving an HTML template at a root URL
Implementing the user model
User schema definition
Name
Created and updated timestamps
Hashed password and salt
Password for auth
Handling the password string as a virtual field
Encryption and authentication
Password field validation
Mongoose error handling
Adding user CRUD APIs
User routes
User controller
Creating a new user
Listing all users
Loading a user by ID to read, update, or delete
Loading
Reading
Updating
Deleting
Integrating user auth and protected routes
Auth routes
Auth controller
Sign-in
Signout
Protecting routes with express-jwt
Protecting user routes
Requiring sign-in
Authorizing signed in users
Auth error handling for express-jwt
Checking the standalone backend
Creating a new user
Fetching the user list
Trying to fetch a single user
Signing in
Fetching a single user successfully
Summary
Adding a React Frontend to Complete MERN
Defining the skeleton application frontend
Folder and file structure
Setting up for React development
Configuring Babel and Webpack
Babel
Webpack
Loading Webpack middleware for development
Loading bundled frontend code
Serving static files with Express
Updating the template to load a bundled script
Adding React dependencies
React
React Router
Material-UI
Rendering a home page view
Entry point at main.js
Root React component
Customizing the Material-UI theme
Wrapping the root component with ThemeProvider and BrowserRouter
Marking the root component as hot-exported
Adding a home route to MainRouter
The Home component
Imports
Style declarations
Component definition
Bundling image assets
Running and opening in the browser
Integrating backend APIs
Fetch for user CRUD
Creating a user
Listing users
Reading a user profile
Updating a user's data
Deleting a user
Fetch for the auth API
Sign-in
Sign-out
Adding auth in the frontend
Managing auth state
Saving credentials
Retrieving credentials
Deleting credentials
The PrivateRoute component
Completing the User frontend
The Users component
The Signup component
The Signin component
The Profile component
The EditProfile component
The DeleteUser component
Validating props with PropTypes
The Menu component
Implementing basic server-side rendering
Modules for server-side rendering
Generating CSS and markup
Sending a template with markup and CSS
Updating template.js
Updating App.js
Hydrate instead of render
Summary
Growing the Skeleton into a Social Media Application
Introducing MERN Social
Updating the user profile
Adding an about description
Uploading a profile photo
Updating the user model to store a photo in MongoDB
Uploading a photo from the edit form
File input with Material-UI
Form submission with the file attached
Processing a request containing a file upload
Retrieving a profile photo
Profile photo URL
Showing a photo in a view
Following users in MERN Social
Following and unfollowing
Updating the user model
Updating the userByID controller method
Adding APIs to follow and unfollow
Accessing the follow and unfollow APIs in views
Follow and unfollow buttons
The FollowProfileButton component
Updating the Profile component
Listing followings and followers
Making a FollowGrid component
Finding people to follow
Fetching users not followed
The FindPeople component
Posting on MERN Social
Mongoose schema model for Post
The Newsfeed component
Listing posts
Listing posts in Newsfeed
Newsfeed API for posts
Fetching Newsfeed posts in the view
Listing posts by user in Profile
API for posts by a user
Fetching user posts in the view
Creating a new post
Creating the post API
Retrieving a post's photo
Fetching the create post API in the view
Making the NewPost component
The Post component
Layout
Header
Content
Actions
Comments
Deleting a post
Interacting with Posts
Likes
The Like API
The Unlike API
Checking if a post has been liked and counting likes
Handling like clicks
Comments
Adding a comment
The Comment API
Writing something in the view
Listing comments
Deleting a comment
The Uncomment API
Removing a comment from the view
Comment count update
Summary
Developing Web Applications with MERN
Building a Web-Based Classroom Application
Introducing MERN Classroom
Updating the user with an educator role
Adding a role to the user model
Updating the EditProfile view
Rendering an option to teach
Adding courses to the classroom
Defining a Course model
Creating a new course
The create course API
Fetching the create API in the view
The NewCourse component
Listing courses by educator
The list course API
Fetching the list API in the view
The MyCourses component
Display a course
A read course API
The Course component
Updating courses with lessons
Storing lessons
Adding new lessons
Adding a lesson API
The NewLesson component
Displaying lessons
Editing a course
Updating the course API
The EditCourse component
Updating lessons
Editing lesson details
Moving the lessons to rearrange the order
Deleting a lesson
Deleting a course
The delete course API
The DeleteCourse component
Publishing courses
Implementing the publish option
Publish button states
Confirm to publish
Listing published courses
The published courses API
The Courses component
Enrolling on courses
Defining an Enrollment model
The create Enrollment API
The Enroll component
The Enrolled Course view
The read enrollment API
The Enrollment component
Tracking progress and enrollment stats
Completing lessons
Lessons completed API
Completed lessons from the view
Listing all enrollments for a user
The list of enrollments API
The Enrollments component
Enrollment stats
The enrollment stats API
Displaying enrollment stats for a published course
Summary
Exercising MERN Skills with an Online Marketplace
Introducing the MERN Marketplace app
Allowing users to be sellers
Updating the user model
Updating the Edit Profile view
Updating the menu
Adding shops to the marketplace
Defining a Shop model
Creating a new shop
The create shop API
Fetching the create API in the view
The NewShop component
Listing shops
Listing all shops
The shops list API
Fetch all shops for the view
The Shops component
Listing shops by owner
The shops by owner API
Fetch all shops owned by a user for the view
The MyShops component
Displaying a shop
The read a shop API
The Shop component
Editing a shop
The edit shop API
The EditShop component
Deleting a shop
The delete shop API
The DeleteShop component
Adding products to shops
Defining a Product model
Creating a new product
The create product API
The NewProduct component
Listing products
Listing by shop
The products by shop API
Products component for buyers
MyProducts component for shop owners
Listing product suggestions
Latest products
Related products
The Suggestions component
Displaying a product
Read a product API
Product component
Editing and deleting a product
Edit
Delete
Searching for products with name and category
The categories API
The search products API
Fetch search results for the view
The Search component
The Categories component
Summary
Extending the Marketplace for Orders and Payments
Introducing cart, payments, and orders in the MERN Marketplace
Implementing a shopping cart
Adding to the cart
Cart icon in the menu
The cart view
The CartItems component
Retrieving cart details
Modifying quantity
Removing items
Showing the total price
Option to check out
Using Stripe for payments
Stripe-connected account for each seller
Updating the user model
Button to connect with Stripe
The StripeConnect component
The stripe auth update API
Stripe Card Elements for checkout
Stripe Customer for recording card details
Updating the user model
Updating the user controller
Creating a new Stripe Customer
Updating an existing Stripe Customer
Creating a charge for each product that's processed
Integrating the checkout process
Initializing checkout details
Customer information
Delivery address
Placing an order
Using Stripe Card Elements
The CardElement component
Adding a button to place an order
Empty cart
Redirecting to the order view
Creating a new order
Defining an Order model
The Order schema
The CartItem schema
Create order API
Decrease product stock quantity
Create controller method
Listing orders by shop
The list by shop API
The ShopOrders component
List orders
The ProductOrderEdit component
Handling actions to cancel a product order
Handling the action to process charge for a product
Handling the action to update the status of a product
APIs for products ordered
Get status values
Update order status
Cancel product order
Process charge for a product
Viewing single-order details
Summary
Adding Real-Time Bidding Capabilities to the Marketplace
Introducing real-time bidding in the MERN Marketplace
Adding auctions to the marketplace
Defining an Auction model
Creating a new auction
The create auction API
Fetching the create API in the view
The NewAuction component
Listing auctions
The open Auctions API
The Auctions by bidder API
The Auctions by seller API
The Auctions component
Editing and deleting auctions
Updating the list view
Edit and delete auction APIs
Displaying the auction view
The read auction API
The Auction component
Adding the Timer component
Implementing real-time bidding with Socket.IO
Integrating Socket.IO
Placing bids
Adding a form to enter a bid
Receiving a bid on the server
Displaying the changing bidding history
Updating the view state with a new bid
Rendering the bidding history
Summary
Advancing to Complex MERN Applications
Integrating Data Visualization with an Expense Tracking Application
Introducing MERN Expense Tracker
Adding expense records
Defining an Expense model
Creating a new expense record
The create expense API
The NewExpense component
Listing expenses
The expenses by user API
The Expenses component
Searching by date range
Rendering expenses
Modifying an expense record
Rendering the edit form and delete option
Editing and deleting an expense in the backend
Visualizing expense data over time
Summarizing recent expenses
Previewing expenses in the current month
The current month preview API
Rendering the preview of current expenses
Tracking current expenses by category
The current expenses by category API
Rendering an overview of expenses per category
Displaying expense data charts
A month's expenses in a scatter plot
The scatter plot data API
The MonthlyScatter component
Total expenses per month in a year
The yearly expenses API
The YearlyBar component
Average expenses per category in a pie chart
The average expenses by category API
The CategoryPie component
Summary
Building a Media Streaming Application
Introducing MERN Mediastream
Uploading and storing media
Defining a Media model
Using MongoDB GridFS to store large files
Creating a new media post
The create media API
The NewMedia component
Retrieving and streaming media
The video API
Using a React media player to render the video
Listing media
The MediaList component
Listing popular media
Listing media by users
Displaying, updating, and deleting media
Displaying media
The read media API
The Media component
Updating media details
The media update API
The media edit form
Deleting media
The delete media API
The DeleteMedia component
Summary
Customizing the Media Player and Improving SEO
Adding a custom media player to MERN Mediastream
The play media page
The component structure
Listing related media
The related media list API
The RelatedMedia component
The PlayMedia component
Customizing the media player
Updating the Media component
Initializing the media player
Custom media controls
Play, pause, and replay
Play next
Loop when a video ends
Volume control
Progress control
Fullscreen
Played duration
Autoplaying related media
Toggling autoplay
Handling autoplay across components
Updating the state when a video ends in MediaPlayer
Server-side rendering with data
Adding a route configuration file
Updating SSR code for the Express server
Using route configuration to load data
Isomorphic-fetch
Absolute URLs
Injecting data into the React app
Applying server-injected data to client code
Passing data props to PlayMedia from MainRouter
Rendering received data in PlayMedia
Checking the implementation of SSR with data
Testing in Chrome
Loading a page with JavaScript enabled
Disabling JavaScript from settings
PlayMedia view with JavaScript blocked
Summary
Developing a Web-Based VR Game
Introducing the MERN VR Game
Game features
Getting started with React 360
Setting up a React 360 project
Key concepts for developing the VR game
Equirectangular panoramic images
3D position – coordinates and transforms
3D coordinate system
Transforming 3D objects
React 360 components
Core components
View
Text
Components for the 3D VR experience
Entity
VrButton
The React 360 API
Environment
Native modules
AudioModule
Location
StyleSheet
VrHeadModel
Loading assets
React 360 input events
Defining game details
Game data structure
Details of VR objects
Static data versus dynamic data
Building the game view in React 360
Updating client.js and mounting to Location
Defining styles with StyleSheet
World background
Adding 3D VR objects
Interacting with VR objects
Rotating a VR object
Animation with requestAnimationFrame
Clicking on the 3D objects
Collecting the correct object on click
Game completed state
Bundling for production and integration with MERN
Bundling React 360 files
Integrating with a MERN application
Adding the React 360 production files
Updating references in index.html
Trying out the integration
Summary
Making the VR Game Dynamic using MERN
Introducing the dynamic MERN VR Game application
Defining a Game model
Exploring the game schema
Specifying the VR object schema
Validating array length in the game schema
Implementing game CRUD APIs
Creating a new game
Listing all games
Listing games by the maker
Loading a game
Editing a game
Deleting a game
Adding a form for creating and editing games
Making a new game
Updating the menu
The NewGame component
Editing the game
The EditGame component
Implementing the GameForm component
Inputting simple game details
Modifying arrays of VR objects
Iterating and rendering the object details form
Adding a new object to the array
Removing an object from the array
Handling the object detail change
The VRObjectForm component
Adding the game list views
Rendering lists of games
The GameDetail component
Playing the VR game
Implementing the API to render the VR game view
Updating the game code in React 360
Getting the game ID from a link
Fetching the game data with the load game API
Bundling and integrating the updated code
Summary
Going Forward with MERN
Following Best Practices and Developing MERN Further
Separation of concerns with modularity
Revisiting the application folder structure
Server-side code
Client-side code
Adding CSS styles
External style sheets
Inline styles
JavaScript Style Sheets (JSS)
Selective server-side rendering with data
When is server-side rendering with data relevant?
Using stateful versus pure functional components
Stateful React components with ES6 classes or Hooks
Stateless React components as pure functions
Designing the UI with stateful components and stateless functional components
Using Redux or Flux
Enhancing security
JSON web tokens – client-side or server-side storage
Securing password storage
Writing test code
Testing tools for full-stack JavaScript projects
Static analysis with ESLint
End-to-end testing with Cypress
Comprehensive testing with Jest
Adding a test to the MERN Social application
Installing the packages
Defining the script to run tests
Adding a tests folder
Adding the test
Generating a snapshot of the correct Post view
Running and checking the test
Optimizing the bundle size
Code splitting
Dynamic import()
Extending the applications
Extending the server code
Adding a model
Implementing the APIs
Adding controllers
Adding routes
Extending the client code
Adding the API fetch methods
Adding components
Loading new components
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
This book explores the development of full-stack JavaScript web applications by combining the power of React with industry-tested server-side technologies, such as Node.js, Express, and MongoDB. The JavaScript landscape has been growing rapidly for some time now. With an abundance of options and resources available in relation to full-stack JavaScript web applications, it is easy to get lost when you need to choose from these frequently changing entities, learn about them, and make them work together to build your own web applications. In an attempt to address this pain point, this book adopts a practical approach to help you set up and build a diverse range of working applications using the popular MERN stack.
This book is for JavaScript developers who may have worked with React but have minimal experience with full-stack development involving Node.js, Express, and MongoDB.
Chapter 1,Unleashing React Applications with MERN, introduces the MERN stack technologies and the applications that will be developed in this book. We will discuss developing web applications with React, Node.js, Express, and MongoDB.
Chapter 2,Preparing the Development Environment, helps you to set up the MERN stack technologies for development. We will explore essential development tools; install Node.js, MongoDB, Express, React, and any other required libraries; and then run code to check the setup.
Chapter 3,Building a Backend with MongoDB, Express, and Node, implements the backend of a skeleton MERN application. We will build a standalone server-side application with MongoDB, Express, and Node.js that stores user details and has APIs for user authentication and CRUD operations.
Chapter 4,Adding a React Frontend to Complete MERN, completes the MERN skeleton application by integrating a React frontend. We will implement a working frontend with React views for interacting with the user CRUD operations and auth APIs on the server.
Chapter 5, Growing the Skeleton into a Social Media Application, builds a social media application by extending the skeleton application. We will explore the capabilities of the MERN stack by implementing social media features, such as post sharing, liking, commenting, following friends, and an aggregated newsfeed.
Chapter 6, Building a Web-Based Classroom Application, focuses on building a simple online classroom application by extending the MERN stack skeleton application. This classroom application will support multiple user roles, the addition of course content and lessons, student enrollments, progress tracking, and course enrollment statistics.
Chapter 7,Exercising MERN Skills with an Online Marketplace, utilizes the MERN stack technologies to develop basic features in an online marketplace application. We will implement buying-and selling-related features with support for seller accounts, product listings, and product search by category.
Chapter 8, Extending the Marketplace for Orders and Payments, focuses on extending the online marketplace we built in the previous chapter by implementing capabilities for buyers to add products to a shopping cart, checkout, and place orders, and for sellers to manage these orders and have payments processed from the marketplace application. We will also integrate Stripe to collect and process payments.
Chapter 9, Adding Real-Time Bidding Capabilities to the Marketplace, focuses on teaching you how to use the MERN stack technologies, along with Socket.IO, to easily integrate real-time behavior in a full-stack application. We will do this by incorporating an auctioning feature with real-time bidding capabilities in the MERN marketplace application.
Chapter 10,Integrating Data Visualization with an Expense Tracking Application, focuses on using MERN stack technologies along with Victory—a charting library for React—to easily integrate data visualization features in a full-stack application. We will extend the MERN skeleton application to build an expense tracking application that will incorporate data processing and visualization features for expense data recorded by a user over time.
Chapter 11,Building a Media Streaming Application, focuses on extending the MERN skeleton application to build a media uploading and streaming application using MongoDB GridFS. We will start by building a basic media streaming application, allowing registered users to upload video files that will be stored on MongoDB and streamed back so that viewers can play each video in a simple React media player.
Chapter 12,Customizing the Media Player and Improving SEO, upgrades the media viewing capabilities of our media application with a custom media player and autoplay media list. We will implement customized controls on the default React media player, add a playlist that can be autoplayed, and improve SEO for the media details by adding selective server-side rendering with data for just the media detail view.
Chapter 13,Developing a Web-Based VR Game, uses React 360 to develop a three-dimensional virtual reality (VR)-infused game for the web. We will explore the three-dimensional and VR capabilities of React 360 and build a simple web-based VR game.
Chapter 14, Making the VR Game Dynamic Using MERN, is where you will build a dynamic VR game application by extending the MERN skeleton application and integrating React 360. We will implement a game data model that allows users to create their own VR games and incorporate the dynamic game data with the game developed using React 360.
Chapter 15,Following Best Practices and Developing MERN Further,reflects on the lessons learned in previous chapters and suggests improvements for further MERN-based application development. We will expand on some of the best practices already applied, such as modularity in the app structure, other practices that should be applied, such as writing test code, and possible improvements, such as optimizing bundle size.
This book assumes that you have familiarity with basic web-based technologies, working knowledge of programming constructs in JavaScript, and a general idea of how React applications work. As you go through the book, you will uncover how these concepts come together when building fully-fledged web applications with React 16.13.1, Node.js 13.12.0, Express 4.17.1, and MongoDB 4.2.5.
In order tomaximize your learning experience while reading through the chapters, it is recommended that you run the associated application code in parallel, maintaining the specified package versions and using the relevant instructions provided in each chapter.
If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
You can download the example code files for this book from your account at www.packt.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.packt.com
.
Select the
Support
tab.
Click on
Code Downloads
.
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 athttps://github.com/PacktPublishing/Full-Stack-React-Projects-Second-Edition. In case 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 athttps://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and 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/support/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 packt.com.
In this part, we get an introduction to MERN and an overview of its different components. Additionally, you will develop an understanding of how to configure your development environment correctly, before you start developing full-fledged web applications with these technologies.
This section comprises the following chapters:
Chapter 1
,
Unleashing React Applications with MERN
Chapter 2
,
Preparing the Development Environment
React may have opened up new frontiers for frontend web development and changed the way we program JavaScript user interfaces, but we still need a solid backend to build a complete web application. While there are myriad options when selecting backend technologies, the benefits and appeal of using a full JavaScript stack are undeniable, especially when there are robust and widely adopted backend technologies such as Node, Express, and MongoDB. Combining the potential of React with these industry-tested, server-side technologies creates a diverse array of possibilities when developing real-world web applications. This book guides you through Setting up MERN (short for MongoDB, Express.js, React, and Node.js) -based web development, to building real-world web applications of varying complexities.
Before diving into the development of these web applications, we are going to answer the following questions in this chapter, so you can use this book effectively to acquire full-stack development skills, and also understand the context behind choosing the MERN stack to build your applications:
What is new in the second edition?
How is this book organized to help master MERN?
What is the MERN stack?
Why is MERN relevant today?
When is MERN a good fit for developing web apps?
MERN stack technologies along with the whole full-stack development ecosystem are continuously growing and improving with increased adoption and usage in the industry. In this edition, we take these new developments into account and update all the applications and corresponding code bases from the first edition.
We use the latest versions and conventions of each technology, library, and module needed for both development-related setup and feature implementations. Additionally, we highlight the use of new features from these technology upgrades such as React Hooks, and JavaScript features such as async/await.
In order to showcase even more possibilities with the MERN stack, we updated the existing marketplace application to add a more advanced feature such as real-time bidding. We also add two new projects, a web-based classroom application and an expense tracking application with data visualization features.
To better understand the content and concepts covered throughout the book, we expand on explanations and provide leads to the latest resources that may help you get a deeper grasp and improve your learning experience.
Besides covering the latest updates to MERN technologies and providing elaborate explanations, the concepts and projects in this book are organized to help you learn from easy to advanced topics with the flexibility to start at any project of your choosing. In the next section, we will discuss the structure of the book and how you can utilize it based on your preference and experience level.
This book aims to help JavaScript developers who have zero-to-some experience with the MERN stack to set up and start developing web applications of varying complexity. It includes guidelines for building out and running the different applications supplemented with code snippets and explanations of key concepts.
The book is organized into five parts, progressing from basic to advanced topics, taking you on a journey of building MERN from the ground up, then using it to develop different applications with simple to complex features, while demonstrating how to extend the capabilities of the MERN stack based on an application's requirements.
Chapter 1,Unleashing React Applications with MERN,andChapter 2,Preparing the Development Environment,set the context for developing web applications in a MERN stack and guide you through setting up your development environment.
Chapter 3,Building a Backend with MongoDB, Express, and Node,andChapter 4,Adding a React Frontend to Complete MERN,show you how to bring the MERN stack technologies together to form a skeleton web application with minimal and basic features. Chapter 5,Growing the Skeleton into a Social Media Application,demonstrates how this skeletal MERN application can act as a base and be easily extended to build a simple social media platform. This ability to extend and customize the base application will be employed with the other applications developed in the rest of this book.
In this part, you will become more familiar with the core attributes of a MERN stack web application by building out two real-world applications—a web-based classroom application inChapter 6, Building a Web-Based Classroom Application, and a feature-rich online marketplace inChapter 7, Exercising MERN Skills with an Online Marketplace,Chapter8,Extending the Marketplace for Orders and Payments,andChapter9,Adding Real-Time Bidding Capabilities to the Marketplace.
Chapter 10,Integrating Data Visualization with an Expense Tracking Application,Chapter 11,Building a Media Streaming Application,Chapter 12,Customizing the Media Player and Improving SEO,Chapter 13, Developing a Web-Based VR Game, andChapter 14,Making the VR Game Dynamic Using MERN,demonstrate how this stack can be used to develop applications with more complex and immersive features, such as data visualization, media streaming, and virtual reality (VR) using React 360.
Finally,Chapter 15,Following Best Practices and Developing MERN Further,wraps up the preceding chapters and applications developed by expanding on the best practices to follow to make successful MERN applications, suggesting improvements and further developments.
You may choose to use the book out of the prescribed order based on your experience level and preference. A developer who is new to MERN can follow the path set out in the book. For a more seasoned JavaScript developer, the chapters in theBuilding MERN from the Ground upsection would be a good place to start setting up the base application, then pick any of the six applications to build and extend.
This structure is set out with the intention to enable hands-on learning for developers from varying backgrounds. In order to maximize this intent, we recommend a practical approach for following along with the material in the book, as described in more detail in the next section.
The content in this book is practical-oriented and covers the implementation steps, code, and concepts relevant to building each MERN application. However, most of the code explanations will refer to specific snippets from files that may contain more lines of code, making up the complete and working application code.
Put simply, it is highly recommended that, rather than attempting to just read through the chapters, you should run the relevant code in parallel, and browse through the application features while following the explanations in the book.
Chapters that discuss code implementations will point to the GitHub repositories containing the complete code with instructions on how to run the code. You can pull the code, install it, and then run it before reading through the chapter:
You should consider the recommended steps outlined here to follow the implementations in this book:
Before diving into the implementation details discussed in the chapter, pull the code from the relevant GitHub repository.
Follow the instructions with the code to install and run the application.
Browse the features of the running application while reading the feature descriptions in the relevant chapter.
With the code running in development mode and also open in the editor, refer to the steps and explanations in the book to get a deeper understanding of the implementations.
This book aims to provide a quick onboarding with the working code for each application. You can experiment with, improve, and extend this code as desired. For an active learning experience, you are encouraged to refactor and modify the code while following the book. In some examples, the book chooses verbose code over succinct and cleaner code because it is easier to reason about for newcomers. In some other implementations, the book sticks with more widely used and traditional conventions over modern and upcoming JavaScript conventions. This is done to minimize disparity when you refer to online resources and documentation while researching the discussed technologies and concepts on your own. These instances, where the code in the book can be updated, serve as good opportunities to explore and grow skills beyond what is covered in the book.
You should now have an overall idea of what to expect in this book and how you can utilize its content and structure to the fullest as we move on to discussing the specifics of the MERN stack and start uncovering its potential.
MongoDB, Express, React, and Node are all used in tandem to build web applications and make up the MERN stack. In this lineup, Node and Express bind the web backend together, MongoDB serves as the NoSQL database, and React makes the frontend that the user sees and interacts with.
All four of these technologies are free, open source, cross-platform, and JavaScript-based, with extensive community and industry support. Each technology has a unique set of attributes, which, when integrated together, make a simple but effective full JavaScript stack for web development.
Since these are independent technologies, it is also important to recognize these as moving parts in your project that need to be configured, combined, and extended with additional parts to meet the specific requirements of your project. Even if you are not an expert in all the technologies in this stack, you need familiarity with each and an understanding of how these can work together.
Node was developed as a JavaScript runtime environment built on Chrome's V8 JavaScript engine. Node made it possible to start using JavaScript on the server side to build a variety of tools and applications beyond previous use cases that were limited to being within a browser.
Node has an event-driven architecture capable of asynchronous, non-blocking I/O (short for Input/Output). Its unique non-blocking I/O model eliminates the waiting approach to serving requests. This allows you to build scalable and lightweight real-time web applications that can efficiently handle many requests.
Node's default package management system, the Node Package Manager or npm, comes bundled with the Node installation. npm gives you access to hundreds of thousands of reusable Node packages built by developers all over the world and boasts that it is currently the largest ecosystem of open source libraries in the world.
However, npm isn't the only package management system at your disposal. Yarn is a newer package manager developed by Facebook and has been gaining popularity in recent years. It can be used as an alternative to npm, with access to all the same modules from the npm registry and more features that are not yet available with npm.
Node will enable us to build and run complete full-stack JavaScript applications. However, to implement an extensible server-side application with web application-specific features such as API routing, we will use the Express module on top of Node.
Express is a simple server-side web framework for building web applications with Node. It complements Node with a layer of rudimentary web application features that provide HTTP utility methods and middleware functionality.
In any web application developed with Node, Express can be used as an API routing and middleware web framework. It is possible to insert almost any compatible middleware of your choice into the request handling chain, in almost any order, making Express very flexible to work with.
In the MERN-based applications that we will develop, Express can be used to handle API routing on the server side, serve static files to the client, restrict access to resources with authentication integration, implement error handling, and, essentially, add on any middleware package that will extend the web application functionality as required.
A crucial functionality in any complete web application is the data storage system. The Express module does not define requirements or put restrictions on integrating databases with a Node-Express web application. Therefore, this gives you the flexibility to choose any database option, be it a relational database such as PostgreSQL or a NoSQL database such as MongoDB.
MongoDB is a top choice when deciding on a NoSQL database for any application. It is a document-oriented database that stores data in flexible, JSON-like documents. This means that fields can vary from document to document and data models can evolve over time in response to changing application requirements.
Applications that place a high priority on availability and scalability benefit from MongoDB's distributed architecture features. It comes with built-in support for high availability, horizontal scaling using sharding, and multi-data center scalability across geographic distributions.
MongoDB has an expressive query language, enabling ad hoc queries, indexing for fast lookups, and real-time aggregation that provides powerful ways to access and analyze data while maintaining performance even when data size grows exponentially.
Choosing MongoDB as the database for a Node and Express web application will make a fully JavaScript-based and standalone server-side application. This will leave you with the option to integrate a client-side interface that may be built with a compatible frontend library such as React to complete the full-stack application.
React is a declarative and component-based JavaScript library for building user interfaces. Its declarative and modular nature makes it easy for developers to create and maintain reusable, interactive, and complex user interfaces.
Large applications that display a lot of changing data can be fast and responsive if built with React, as it takes care of efficiently updating and rendering just the right user interface components when specific data changes. React does this efficient rendering with its notable implementation of a virtual DOM, setting React apart from other web user interface libraries that handle page updates with expensive manipulations directly in the browser's DOM.
Developing user interfaces using React also forces frontend programmers to write well-reasoned, modular code that is reusable and easier to debug, test, and extend.
Since all four technologies are JavaScript-based, these are inherently optimized for integration. However, how these are actually put together in practice to form the MERN stack can vary based on application requirements and developer preferences, making MERN customizable and extensible to specific needs. Whether this stack is a relevant option for your next full-stack web project not only depends on how well it can meet your requirements, but also on how it is currently faring in the industry and where these technologies are headed.
JavaScript has come a long way since its inception, and it is ever-growing. MERN stack technologies have challenged the status quo and broken new ground for what is possible with JavaScript. But when it comes to developing real-world applications that need to be sustainable, is it a worthy choice? Some of the reasons that make a strong case for choosing MERN for your next web application are briefly outlined in the following sections.
As JavaScript is used throughout, developers don't need to learn and change gears frequently to work with very different technologies. This also enables better communication and understanding across teams working on different parts of the web application.
Consistency across the stack also makes it easy to learn and work with MERN, reducing the overhead of adopting a new stack and the time to develop a working product. Once the working base of a MERN application is set up and a workflow established, it takes less effort to replicate, further develop, and extend any application.
Organizations of all sizes have been adopting the technologies in this stack based on their needs because they can build applications faster, handle highly diverse requirements, and manage applications more efficiently at scale.
Developer communities surrounding the very popular MERN stack technologies are quite diverse and are growing on a regular basis. With lots of people continuously using, fixing, updating, and willing to help grow these technologies, the support system will remain strong for the foreseeable future. These technologies will continue to be maintained, and resources are very likely to be available in terms of documentation, add-on libraries, and technical support.
The ease and benefits of using these technologies are already widely recognized. Because of the high-profile companies that continue adoption and adaptation, and the growing number of people contributing to the code bases, providing support, and creating resources, the technologies in the MERN stack will continue to be relevant for a long time to come.
In order to determine whether this widely adopted stack will meet the specific requirements of your project, you can explore the extent of feature implementations possible with this group of technologies. In the next section, we will highlight a few aspects of this stack and also several features of the book's example applications that demonstrate the diverse array of options that are available with these technologies.
Given the unique features attributed to each technology, along with the ease of extending functionalities of this stack by integrating other technologies, the range of applications that can be built with this stack is actually quite vast.
These days, web applications are, by default, expected to be rich client apps that are immersive, interactive, and don't fall short on performance or availability. The grouping of MERN strengths makes it perfect for developing web applications that meet these very aspects and demands.
Moreover, novel and upcoming attributes of some of these technologies, such as low-level operation manipulation with Node, large file streaming capabilities with MongoDB GridFS, and VR features on the web using React 360, make it possible to build even more complex and unique applications with MERN.
It may seem reasonable to pick specific features in the MERN technologies and argue why they don't work for certain applications. However, given the versatile nature of how a MERN stack can come together and be extended, these concerns can be addressed in MERN on a case-by-case basis. In this book, we will demonstrate how to make such considerations when faced with specific requirements and demands in the application being built.
To demonstrate the breadth of possibilities with MERN and how you can easily start building a web application with varying features, this book will showcase everyday-use web applications alongside complex and rare web experiences.
For the first MERN application, we will build a basic social media application inspired by Twitter and Facebook, as follows:
This social media platform will implement simple features such as post sharing, liking and commenting, following friends, and an aggregated news feed.
Remote or online learning is a common practice these days, with both instructors and students utilizing internet connectivity to teach and learn over online platforms. We will implement a simple web-based classroom application using MERN, which will look like the following screenshot:
This classroom will have features that allow instructors to add courses with lessons, while students can enroll in these courses and track their progress.
All sorts of e-commerce web applications are abundant on the internet, and they will not go out of style anytime soon. Using MERN, we will build a comprehensive online marketplace application with basic-to-advanced e-commerce features. The following screenshot shows the completed home page of the marketplace with product listings:
The features of this marketplace application will cover aspects such as support for seller accounts, product listings, a shopping cart for customers, payment processing, order management, and real-time bidding capabilities.
Adding data visualization to any data-intensive application can boost its value considerably. We will extend MERN with an expense-tracking application to demonstrate how you can incorporate data visualization features, including graphs and charts, in a full-stack MERN application. The following screenshot shows the completed home page of the expense tracker application with an overview of the user's current expenses:
With this application, users will be able to keep track of their day-to-day expenses. The application will add the expenses incurred over time. Then, the application will extract data patterns to give the users a visual representation of how their expense habits fare as time progresses.
To test out some advanced MERN capabilities, a more immersive application, such as a media streaming application, is the next pick. The following screenshot shows the home page view containing a list of popular videos added to this platform, which is inspired by features from Netflix and YouTube:
In this media streaming application, we will implement content uploading and viewing capabilities with a media content upload feature for content providers, and real-time content streaming for viewers.
With frameworks such as React 360, which is built on top of React, it is possible to apply web VR and 3D capabilities to React's user interfaces. We will explore how to create rare web experiences with React 360 in MERN by putting together a basic VR game application for the web, as shown in the following screenshot:
Users will be able to play the VR games and also make their own games with this web-based application. Each game will have animated VR objects placed across a 360 world, and players will have to find and collect these objects to complete the game.
Following along with the implementations for these diverse applications in the book will teach you how to combine, extend, and use MERN stack technologies to build full-stack web applications, and also reveal a diverse range of options for your own full-stack projects.
In this chapter, we discovered the context for developing web applications in the MERN stack and how this book will help you to develop with this stack. MERN stack projects integrate MongoDB, Express, React, and Node to build web applications. Each of the technologies in this stack has made relevant strides in the world of web development. These are widely adopted and continue to improve with the support of growing communities. It is possible to develop MERN applications with diverse requirements, ranging from everyday-use applications to more complex web experiences. The practical-oriented approach in this book can be used to grow MERN skills from basic to advanced, or for diving right into building more complex applications.
In the next chapter, we will start gearing up for MERN application development by learning how to set up the development environment with each MERN stack technology, and also write code for a MERN starter application to ensure the setup on your system is correct.
Before building applications with the MERN stack, we first need to prepare the development environment with each technology, and also with tools to aid development and debugging. Working with this stack requires that you make different technologies and tools work well together, and given the many options and resources available on this topic, it can seem like a daunting task to figure out how it all comes together. This chapter guides you through the workspace options, the essential development tools, how to set up the MERN technologies in your workspace, and how to check this setup with actual code.
We are going to cover the following topics:
Selecting development tools
Setting up MERN stack technologies
Checking your development setup
