Statistics
19
Views
0
Downloads
0
Donations
Uploader

高宏飞

Shared on 2025-12-24
Support
Share

AuthorGrace Huang

No description

Tags
No tags
Publish Year: 2023
Language: 英文
File Format: PDF
File Size: 18.7 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
(This page has no text content)
DY N A M I C T R I O : B u i l d i n g We b A p p l i c a t i o n s w i t h R e a c t , N e x t . j s & T a i l w i n d By Grace Huang 1
Copyright © 2023 Grace Huang 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, electronic, mechanical, photocopying, recording, or otherwise, without the publisher's prior written permission. The information in this book is provided for educational and informational purposes only. It is not intended as a substitute for professional advice. The author and publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book. Trademarks: All terms mentioned in this book known as trademarks or service marks have been appropriately capitalized. The author cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. First Edition: April 2023 2
To my parents, who gave me my first computer in 1999. 3
Introduction 7 End Goal 8 Structure 8 Prerequisites 9 Assumptions 10 Formats of the Book 10 Code Examples 11 Suggestions 11 Chapter 1: Introduction to React 12 What is React? 12 Understanding the Virtual DOM 12 Components 15 JSX 16 Props 17 State 17 Conclusion 19 Chapter 2: Introduction to Next.js 20 What is Next.js? 20 Server-Side Rendering 21 Static Site Generation 23 Image Optimization 24 Built-in Routing 25 Conclusion 31 Chapter 3: Introduction to Tailwind CSS 32 What is Tailwind CSS? 32 Understanding Utility Classes 33 Styling Elements with Tailwind CSS 35 4
Common Utility Classes 36 Responsive Design with Tailwind CSS 40 Conclusion 44 Chapter 4: Building “Hello World” 46 Goals of this Chapter 46 The Outcome of this Chapter 46 Creating a Project 46 Configuring TypeScript 51 Setting Up Tailwind CSS 52 Code Example 55 Conclusion 55 Chapter 5: Building A Personal Website 56 Goals of this Chapter 56 Requirements of the Web App 56 Setting Up 58 Creating the Pages 59 Creating A Layout 62 Creating Navigation Bar 64 Making the Navigation Bar Dynamic 69 Building the Footer 73 Building the Projects Page 75 Making the Page SEO-Friendly 85 Code Example 94 Conclusion 94 Chapter 6: Building A Weather App 97 Goals of this Chapter 97 Requirements of the Weather App 97 5
System Design 98 Task Breakdown 101 Setting Up the Next.js App 102 Setting up OpenWeather API and Acquiring the API key 104 Building the Search Page 108 Styling the Search Page 110 Downloading the City JSON 112 Defining Data Interface for City Data 113 Implementing the City Suggestion Endpoint 114 Building the Detail Page 124 Defining Data Interface for Weather Data 127 Implementing Request to OpenWeather API 130 Displaying An Image 132 Styling the Detail page 136 Code Example 138 Conclusion 138 Chapter 7: Deploying to Production 141 Goals of this Chapter 141 Deploying to Production 141 Setting up Domain 148 Monitoring 155 Conclusion 160 About Author 162 6
I N T R O D U C T I O N I have a long history with web development. In 1999, when I was in high school, my parents gave me my first computer. I started tinkering with Microsoft FrontPage and built my early websites: fan websites for my favorite soccer players. To this day, I still think FrontPage was a powerful tool that made many amateurs like me get into Web 1.0. What fascinated me about web development was how a few lines of HTML code in a plain text editor could turn into a web page. In 2006, I landed my first job as a web developer in New York City. At that time, jQuery was the prevalent utility in the industry. Despite the co-existence of many fragmented browsers, jQuery unified the DOM standards and brought backward compatibility. In 2008, while working at a startup, I co-wrote a JavaScript Framework from scratch with a group of hardcore front-end engineers. It was pretty cool! Even though some people disliked JavaScript for its lack of types and believed it would be short-lived, I loved how flexible and ubiquitous this language was. To this day, JavaScript is still not dead yet, but even more popular. When I was running my business Roxy in 2016, React and Bootstrap were my primary go-to for building websites. React finally united HTML and JavaScript, and Bootstrap standardized the styles of UI components on both web and mobile. Fast forward to 2023, React, Next.js, and Tailwind are now the go-to frameworks for building web applications. Almost every day, new applications pop up around the world using this trio. These frameworks have become stepping stones for engineers and entrepreneurs to launch their products at a speed that I could never have imagined 20 years ago. This is why I wrote this book: to demonstrate how you can effectively utilize these three tools to build web applications, regardless of whether you are a software engineer helping adopt new web stacks or an entrepreneur starting a software business. 7
End Goal After reading the book, you should be able to create web applications on your own and deploy them to the server, with the three tools: React, Next.js, and Tailwind CSS, and have the applications running under your domains Web development will no longer be a mystery to you, and you will be familiar with the end-to-end process. Structure Over the years, I have found that the most effective way to teach others is through examples. Good examples are like good stories - they become the vehicle for showcasing the knowledge and skills you are acquiring. You may forget how a new concept was described, but you will always remember how you put it into practice. With this same spirit, this book will focus more on doing, through real- time projects. Part 1 The first part of this book will focus on getting you familiar with the powerful trio of React, Next.js, and Tailwind, and what makes each of them individually powerful. The chapters in this part will cover: • Chapter 1: Introduction to React • Chapter 2: Introduction to Next.js • Chapter 3: Introduction to Tailwind CSS However, we will not dive into the details of how to use them just yet. That will be covered in Part 2. 8
If you are already familiar with any of the concepts, feel free to skip the sections of the chapter. Part 2 The second part of this book will be a step-by-step walkthrough of real- life web projects, guiding you through the process of creating these applications from scratch using the powerful trio of React, Next.js, and Tailwind. The chapters in this part will cover: • Chapter 4: Building “Hello World” • Chapter 5: Building A Personal Website • Chapter 6: Building A Weather App Part 3 The third part of this book will cover the necessary steps for deploying your application to production. The chapter in this part will cover: • Chapter 7: Deploying to Production Prerequisites To follow along with this book, you will need the following: • Internet access • A computer running either Mac or Windows • A Unix-specific Command Line Interface (CLI), aka Command Prompt, such as Terminal on Mac or Git Bash on Windows 9
• A text editor, such as Sublime or VS Code • Node.js installed (version 14.6.0 or later) Assumptions This book assumes that you are new to web development with React, Next.js, and Tailwind, but not necessarily new to programming in general. If you have prior programming experience in other languages or domains, it should be easier to follow the steps in the book. In addition, in this book, we will not cover building data models or setting up databases, which are sizable topics themselves. We will focus on building user interfaces. Finally, note that this book utilizes React version 18, Next.js version 13, and Tailwind version 3. Using different versions of these frameworks may result in variations. Formats of the Book As you follow along with the projects in the book, use these visual signals as a guide: : this means a step. You can follow it throughout the book for the actionable steps, and skim through other parts to save time. : this means a command line. Let me explain: this means a deeper explanation for something being used in code or description. Italic text often corresponds to keywords in the figures and code. The code highlighted in gray refers to the area of focus or change. All the screenshots in this book are captured from a Mac computer. 1 0
In this book, the term "Command Prompt" refers specifically to the Command Line Interface (CLI) commonly used in Unix-based operating systems. On Mac, it is referred to as "Terminal", while on Windows, it may refer to "Git Bash" or "Cygwin", which are popular CLI alternatives for Windows users. Code Examples You can access all the code examples from this book for free at https:// github.com/higracehuang. If you ever get lost in the book, the code examples will always be the best resource to get back on track. A direct link to the project repository will be provided at the end of each chapter in Part 2. Suggestions Please don't hesitate to provide feedback if anything is unclear or if you spot any typos in this book. You can contact me through any of the following methods: Email: higracehuang@gmail.com Twitter: https://twitter.com/imgracehuang LinkedIn: https://www.linkedin.com/in/lghuang/ Ready? Let’s dive right in! 1 1
C H A P T E R 1 : I N T R O D U C T I O N T O R E A C T What is React? React is a JavaScript library for building user interfaces based on UI components. It is named for its ability to react to changes in data and render the user interface accordingly. It reacts to changes in state and props and updates the UI to reflect those changes. Let me explain: History of React In 2011, Jordan Walke, a software engineer at Facebook, created React to address the challenge of managing constant updates and changes to the News Feed feature. The existing approach, which involved directly manipulating the DOM, was inefficient at handling frequent updates. To build a more efficient approach, Walke experimented with a new way of building UI, resulting in the creation of React. React uses a virtual DOM to track changes to the user interface. When data changes, React updates the virtual DOM and compares it to the previous version. It then calculates the minimum number of changes required to bring the real DOM up to date with the virtual DOM. This approach makes React efficient and fast, even with large and complex user interfaces. In this chapter, we will cover the basics of React, including components, JSX, props, and state, as well as the concept of virtual DOM. Understanding the Virtual DOM 1 2
The React JavaScript library uses a programming concept called the Virtual DOM. When a user interacts with a web page, the browser updates the DOM (Document Object Model) to reflect those changes. However, updating the DOM can be a slow and expensive operation, especially for large and complex web pages. This is because the DOM is represented as a tree data structure, and after a change is made, the updated element and its children must be re-rendered to update the application's user interface (UI). This re-rendering, or re-painting, of the UI, can be slow and contribute to performance issues. To avoid these performance issues, React uses a Virtual DOM. The Virtual DOM is an in-memory representation of the actual DOM. It is a lightweight JavaScript object that contains all the necessary properties and attributes of the elements on a web page. When a change occurs in the user interface, React updates the Virtual DOM first, which is much faster than updating the actual DOM. Then, React compares the previous and updated Virtual DOMs and determines the minimum set of changes required to update the actual DOM. Finally, React applies those changes in a batch update to the actual DOM. 1 3
In Figure 1-1, the red circles represent the UI elements that have had their state changed. Node C, in particular, has changed, and because it has two leaf nodes (Node E and Node F), both nodes must be redrawn as well. React uses a virtual DOM to update the UI efficiently. Instead of triggering changes to the actual DOM, React creates a DOM structure in memory, applies the changes in the virtual DOM, and computes the difference between the previous version of the virtual DOM tree and the current virtual DOM tree. Once the differences are identified (Node C, Node E, and Node F), React applies the minimal set of changes necessary to update the actual DOM to reflect the new state of the component. Without the virtual DOM, updating the DOM can be slow and inefficient, especially when dealing with large, complex UIs or frequent Figure 1-1 How React uses Virtual DOM to update UI 1 4
updates. By using the Virtual DOM, React minimizes the number of updates to the actual DOM, resulting in faster and more efficient web applications. Components React components are self-contained modules used to create user interfaces. Like LEGO pieces, they function as building blocks, representing parts of a larger UI that can be reused throughout an application to improve efficiency and reduce code duplication. Here's an example of a simple React app that uses components: import React from 'react'; // Header component function Header() { return ( <header> <h1>My React App</h1> </header> ); } // Main component function Main() { return ( <main> <h2>Welcome to my React App!</h2> <p>This is the main content area.</p> </main> ); } // Footer component function Footer() { return ( <footer> <p>&copy; 2023 My React App</p> </footer> ); } // App component that uses the Header, Main, and Footer components function App() { return ( <div> <Header /> <Main /> <Footer /> </div> ); } export default App; 1 5
In this example, we have three components: Header, Main, and Footer. Each component is a building block that can be combined to create a more complex application. The App component uses these three components to create a simple layout with a header, main content area, and footer. JSX JSX is React's syntax for creating components. It looks like HTML, but instead of just describing the structure of a webpage, you can also include JavaScript code to make your components dynamic and interactive. Here is an example that demonstrates how JSX can be used to create dynamic and interactive web pages: import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return ( <div> <h1>Count: {count}</h1> <button onClick={handleClick}>Increment</button> </div> ); } export default Counter; In this example, we create a Counter component in React using JSX. The component stores the current count in a state variable named count and updates the count using a function called handleClick when the user clicks the Increment button. Although the JSX code resembles HTML, we've included JavaScript code within curly braces {} to add interactivity to the component. Specifically, we use the count and handleClick variables to display the current count and handle user input. 1 6
By using JSX, we can create highly interactive components that respond to user input in real-time. This makes it easy to build dynamic web applications that provide an excellent user experience. Props In React, "props" is short for "properties" and is used to pass data from a parent component to a child component. For example, a parent component could pass the string "Hello, world!" as a prop to a child component that displays that text. Props can be any type of data, including strings, numbers, booleans, objects, and functions. For example, consider the following component: function Greeting(props) { return <h1>Hello, {props.name}!</h1>; } Here, the Greeting component takes a props parameter, which is an object containing the name property. The name property is used to render a greeting message. When the component is used, it can be passed a name prop like so: <Greeting name="John" /> In this example, the name prop is passed to the Greeting component with a value of "John". The component then renders the message "Hello, John!" using the name prop. State In React, a state is an object that contains data that determines the behavior and rendering of a component. For example, a component that displays a counter might have a state object with a count property that keeps track of the current count. 1 7
When the state changes, React will automatically re-render the component with the new state, updating the user interface as necessary. This makes it easy to create dynamic and interactive UIs that respond to user input and other events. You can define the state in a component using the useState hook. For example: import React, { useState } from 'react'; function Example() { const [name, setName] = useState(''); const [age, setAge] = useState(0); const [email, setEmail] = useState(''); const handleNameChange = (e) => { setName(e.target.value); }; const handleAgeChange = (e) => { setAge(e.target.value); }; const handleEmailChange = (e) => { setEmail(e.target.value); }; return ( <div> <input type="text" placeholder="Name" value={name} onChange={handleNameChange} /> <input type="number" placeholder="Age" value={age} onChange={handleAgeChange} /> <input type="email" placeholder="Email" value={email} onChange={handleEmailChange} /> <p>{name} is {age} years old and their email is {email}.</p> </div> ); } export default Example; The Example component manages three states: name, age, and email. Each state is initialized using the useState hook, and its value can be updated using the corresponding setter function (setName, setAge, and setEmail). The handleNameChange, handleAgeChange, and handleEmailChange functions are event handlers that update the state value when the input value changes. Finally, the component renders the input fields and displays the current state values. 1 8
The above is a preview of the first 20 pages. Register to read the complete e-book.