(This page has no text content)
The Road to React The React.js in JavaScript Book (2025 Edition) Robin Wieruch This book is available at https://leanpub.com/the-road-to-learn-react This version was published on 2025-05-21 This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. © 2016 - 2025 Robin Wieruch
Tweet This Book! Please help Robin Wieruch by spreading the word about this book on Twitter! The suggested tweet for this book is: I am going to learn #ReactJs with The Road to React by @rwieruch Join me on my journey https://roadtoreact.com The suggested hashtag for this book is #ReactJs. Find out what other people are saying about the book by clicking on this link to search for this hashtag on Twitter: #ReactJs
Contents Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 FAQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Who is this book for? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 How to read the book? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Fundamentals of React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Hello React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Setting up a React Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Project Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 npm Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Meet the React Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 React JSX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Lists in React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Meet another React Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 React Component Instantiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 React DOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 React Component Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Handler Function in JSX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 React Props . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 React State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 Callback Handlers in JSX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 Lifting State in React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 React Controlled Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Props Handling (Advanced) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 React Side-Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 React Custom Hooks (Advanced) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 React Fragments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 Reusable React Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 React Component Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Imperative React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Inline Handler in JSX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 React Asynchronous Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
CONTENTS React Conditional Rendering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 React Advanced State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 React Impossible States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 Data Fetching with React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Data Re-Fetching in React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Memoized Functions in React (Advanced) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 Explicit Data Fetching with React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 Third-Party Libraries in React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Async/Await in React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 Forms in React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 Forms with Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 A Roadmap for React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 Styling in React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 CSS in React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 CSS Modules in React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 Styled Components in React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 SVGs in React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 React Maintenance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 Performance in React (Advanced) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 TypeScript in React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 Testing in React . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 React Project Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 Real World React (Advanced) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 Reverse Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 Remember Last Searches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 Paginated Fetch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 Deploying a React Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 Build Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 Deploy to Firebase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Foreword I’ve been a React developer since its inception. When I first encountered it, there was an air of mystery around it, as it distinguished itself from competitors by emphasizing the exclusive use of components. Over a decade later, I can’t imagine working with any other framework in the near future. React continues to reinvent itself while pushing other frameworks to evolve as well. As a freelance web developer collaborating closely with companies, React is my indispensable daily companion, enhancing my productivity on every project. “The Road to React” debuted in 2016, and since then, I’ve almost rewritten it annually. This book teaches the core principles of React, guiding you through building a practical application in pure React without complex tooling. It covers everything from setting up the project to deploying it on a server. Each chapter includes additional recommended reading and exercises. By the end, you’ll have the skills to develop your own React applications. In The Road to React, I establish a solid foundation before exploring the broader React ecosystem. The book clarifies general concepts, patterns, and best practices for real-world React applications. Ultimately, you’ll learn to build a React application from scratch, incorporating features such as pagination, client-side and server-side searching, and advanced UI interactions like sorting. My hope is that this book conveys my passion for React and JavaScript, helping you embark on your journey with confidence. I hope you enjoy reading this book and that it helps you get started. If you have any feedback, feel free to reach out to me on Twitter at @rwieruch¹ or LinkedIn². I would love to hear from you! Since lots of sweat and tears went into writing this book, I would appreciate it if you could share it with your friends and coworkers. It would mean a lot to me and help me reach more people who want to learn web development. I dedicate this book to all the aspiring web developers eager to learn and grow. Happy coding! ¹https://x.com/rwieruch ²https://tinyurl.com/c2y283mk
Foreword 2 About the Author I am a German full-stack developer with a passion for learning and teaching JavaScript. Following the completion of my Master’s Degree in computer science, I immersed myself in the startup world, extensively using JavaScript both professionally and in my free time. Collaborating with an exceptional team of engineers in Berlin/Germany, we developed large-scale JavaScript applications which sparked my interest in sharing this knowledge with others. During this time, I regularly authored articles on web development for mywebsite. Positive feedback from readers seeking to learn frommy articles motivated me to refine my writing and teaching style. With each article, my ability to effectively educate others continued to grow. Witnessing students thrive by providing them with clear objectives and quick feedback loops is particularly fulfilling. Presently, I operate as a freelance developer, closely working with companies on their products as freelancer or consultant. More information about collaborating with me can be found on my website³. ³https://www.robinwieruch.de/
Foreword 3 FAQ How to get updates? Stay informed about the latest updates through myNewsletter⁴. Rest assured that I prioritize sharing only high-quality content. Is the learning material up-to-date? Unlike traditional programming books that quickly become outdated, this self-published book allows for prompt updates whenever new versions of relevant tools or technologies are released. You’ll always have access to the latest information. Can I get a digital copy of the book if I’ve purchased it on Amazon? Did you know that it’s also available on my website? To access the content there, simply send me an email with proof of your Amazon purchase. I’ll then unlock the content for you on my website where you’ll always have access to the latest version of the book. I truly appreciate your support, so a review on Amazon would be fantastic! Why is the print version so large? If you’ve acquired the print version of the book, consider making notes directly in its pages. The deliberate choice to keep the printed book extra-large was made to provide ample space for extensive code snippets and to afford you sufficient room for your annotations and personal notes. This size decision was crafted with the intention of enhancing your overall reading and learning experience. Why is the book written like a long-read tutorial? The unconventional manner in which this book is written and structured might come as a surprise to thosemore accustomed to the conventional format of programming texts.When I first started coding, there was a scarcity of practical, hands-on resources available. As a learner, I found great value in materials that provided step-by-step instructions, guiding me through not only the ‘what’ and ‘how’ but also the ‘why’ behind each concept. With the goal of replicating this immersive learning experience, I’ve taken on the task of self-publishing, hoping to extend this valuable knowledge- sharing opportunity to fellow developers within our community. Where do I get help? Should you come across any difficult sections in the code, I encourage you to join the community on Discord⁵, where you can share your thoughts and feedback with other learners. ⁴https://rwieruch.substack.com/ ⁵https://discord.gg/ssE5VMSPkV
Foreword 4 Who is this book for? JavaScript Beginners JavaScript beginners with a basic understanding of JS, CSS, and HTML: If you’ve just started web development and have a basic grasp of JS, CSS, and HTML, this book will provide everything you need to learn React. However, if you feel there’s a gap in your JavaScript knowledge, don’t hesitate to review that topic before continuing with the book. You will find many references to fundamental JavaScript concepts within the book. JavaScript Veterans JavaScript veterans coming from jQuery: If you’ve extensively used JavaScript with jQuery, MooTools, or Dojo in the past, the new JavaScript landscape may seem overwhelming as you get back on track. However, most of the fundamental concepts haven’t changed–it’s still JavaScript and HTML under the hood. This book will give you a solid starting point for React. JavaScript Enthusiasts JavaScript enthusiasts with knowledge of other modern SPA frameworks: If you’re coming from Angular or Vue, therewill be differences in howyouwrite applicationswith React. However, all these frameworks share the same fundamentals of JavaScript and HTML. After adjusting your mindset to React’s approach, you should have no trouble adopting it. Non-JavaScript Developers If you’re coming from another programming language, you’re likely more familiar with the various aspects of programming. After learning the fundamentals of JavaScript and HTML, you should have a smooth time picking up React with this book. Designers and UI/UX Enthusiasts If your main profession is in design, user interaction, or user experience, don’t hesitate to pick up this book. You may already be quite familiar with HTML and CSS, which is a plus. After covering some more JavaScript fundamentals, you’ll be well-equipped to work through the rest of the book. These days, UI/UX is increasingly intertwined with implementation, and React often handles these details. Knowing how things work in code will be a valuable asset. Team Leads, Product Owners, or Product Managers If you’re a team lead, product owner, or product manager in your development department, this book will provide a clear breakdown of the essential parts of a React application. Each section explains a React concept, pattern, or technique that adds a feature or improves the overall architecture. It’s a well-rounded reference guide for React.
Foreword 5 How to read the book? Most programming books are high-level and delve into technical details, but they often lack the ability to get their readers into coding. This book may differ from those you are used to reading in this domain because it attempts to teach aspiring developers actual programming. I try to strike a balance between being pragmatic, by providing you with the tools to get the job done, and being detail-oriented, by giving you the necessary information to understand these tools and how they are used in practice. Take Notes If you have a print version of the book, do not hesitate to underline paragraphs, write notes, or annotate code snippets. That’s why it has such a large size in the first place. If you don’t have a print version, keep a notebook on the side for your learnings. Taking notes fortifies what you have learned, and you can always come back to them. With every new learning, you will get a better understanding of the big picture and how the smaller pieces fit together, so it’s a great exercise to write down your learnings on a piece of paper. Code Code Code Every section introduces you to a new topic in a pragmatic way. For this reason, just reading through the section does not suffice to become a developer because there are lots of things going on in one section alone. So you shouldn’t rush from section to section. Instead, I recommend having a computer by your side to code along the way. Do not just copy and paste code; instead, type it yourself. Do not be satisfied when you just use the code from the book; instead, experiment with it. See what breaks the code and how to fix it. See how certain changes affect the result. And see how you can extend or even improve the code by adding a few lines to it. That’s what coding is all about, after all. It does not help you to rush through the book if you haven’t written a line of code. So get your hands dirty and do more coding than reading! Anticipate There will be many coding problems presented in this book. Sometimes, I will give you the option to solve things yourself before reading about the solution in the next paragraph or code snippet. However, it breaks the flow of repeating myself, so I keep these encouragements to a minimum. Instead, I am hoping for your eagerness to jump ahead. Try to solve things before I get the chance to present you with the solution. Only by trying, failing, and solving a problem will you become a better developer. Take Breaks Since every section introduces you to a new topic, it’s easy to forget the learnings from the previous section. In addition to coding along with every section, I recommend taking breaks between the sections to allow the learnings to sink in. Read the section, code along the way, code even a bit more if you like, and then rest. Think about your learnings while taking a walk outside or speak with someone about what you have learned, even if this other person is not into coding. After all, taking breaks is always essential if you want to learn something new.
Fundamentals of React In the initial phase of this learning journey, we’ll explore the essential foundations of React, guiding you through the creation of your first React project. As we progress, we’ll dive deeper into React’s capabilities, implementing practical features such as client- and server-side searching, remote data fetching, and advanced state management. This hands-on approach mirrors the development of a real-world web application. By the end, you’ll have a fully functional React application that seamlessly interacts with real-world data.
Fundamentals of React 7 Hello React Single-page applications (SPA⁶) have gained popularity with first-generation SPA frameworks like Angular (byGoogle), Ember, Knockout, and Backbone. These frameworksmade it easier to buildweb applications that went beyond vanilla JavaScript and jQuery. React, introduced by Facebook in 2013, emerged as another solution for SPAs, offering a powerful way to build modern web applications in JavaScript. Let’s take a trip back in time before SPAs existed. In the past, websites and web applications were server-rendered. When a user accessed a URL in a browser, a request was sent to a web server, which returned an HTML file along with its associated CSS and JavaScript files. After some network delay, the user would see the rendered HTML and could begin interacting with it. Each subsequent page transition repeated this process. In this model, the server handled most essential tasks, while the client played a minimal role, primarily rendering pages. Basic HTML and CSS structured and styled the application, while JavaScript–often in the form of jQuery–enabled interactions (e.g., toggling a dropdown) or advanced styling (e.g., positioning a tooltip). In contrast, SPA frameworks shifted the focus from the server to the client. In SPAs, the server primarily delivers JavaScript over the network, along with a minimal HTML file. The browser executes the linked JavaScript files, rendering the entire application dynamically using HTML and CSS while relying on JavaScript for interactions. In its most extreme form, a user visiting a URL receives a small HTML file and a larger JavaScript file. After a brief network and rendering delay, JavaScript renders the content in the browser. Subsequent page transitions no longer require additional server requests for new files; instead, the initially loaded JavaScript dynamically renders new pages. React, along with other SPA solutions, played a pivotal role in this transformation. Essentially, an SPA is a structured bundle of JavaScript, organized into folders and files, forming a complete application. An SPA framework like React provides the tools to architect this JavaScript-driven application.When a user visits a web application’s URL, the JavaScript-based application is delivered once over the network. From that point on, React–or any other SPA framework–takes over, rendering everything in the browser as HTML and handling user interactions with JavaScript. With React’s rise, the concept of components became central. Each component encapsulates its visual and functional aspects using HTML, CSS, and JavaScript. Once defined, components can be combined into a hierarchy to build a complete application. While React primarily focuses on components as a library, its flexible ecosystem allows it to function as a framework. With a streamlined API, a stable yet evolving ecosystem, and a supportive community, React is ready to welcome you with open arms! :-) Exercises • Read more about Websites and Web Applications⁷. ⁶https://bit.ly/3BZOL1o ⁷https://www.robinwieruch.de/web-applications/
Fundamentals of React 8 • Watch React.js: The Documentary⁸. • Read more about JavaScript fundamentals needed for React⁹. • Optionally, if you need a motivational boost: – Read more about how to learn a framework¹⁰. – Read more about how to learn React¹¹. ⁸https://bit.ly/3xrvxkI ⁹https://www.robinwieruch.de/javascript-fundamentals-react-requirements/ ¹⁰https://www.robinwieruch.de/how-to-learn-framework/ ¹¹https://www.robinwieruch.de/learn-react-js/
Fundamentals of React 9 Requirements To navigate this book effectively, you should have a basic understanding of web development, including HTML, CSS, and JavaScript. Familiarity with APIs¹² is helpful, as they will be covered later. Additionally, you’ll need the following coding tools to follow along. Editor and Terminal For this learning experience, I recommend using an IDE¹³, such as Visual Studio Code (VSCode), especially for beginners. It provides an advanced editor with an integrated terminal and is the most popular choice among web developers. I’ve created a setup guide¹⁴ to help you get started with general web development. It includes all the details and is kept separate from this book since it offers options for both Windows and macOS users. Optionally, you can also check out my complete macOS setup guide¹⁵. If you prefer not to set up an editor and terminal on your local machine, CodeSandbox¹⁶ is a viable online alternative. While CodeSandbox is great for sharing code, a local setup is a better learning environment for building web applications. If you plan to develop applications professionally, a local setup will eventually be required. Throughout this book, I will use command line as a general term for command line tool, terminal, and integrated terminal. Similarly, editor, text editor, and IDE will be used interchangeably, depending on your setup. Additionally, I recommend using GitHub to manage projects as we go through the exercises. I’ve provided a short guide¹⁷ on using Git and GitHub. Version control is invaluable–it allows you to track changes, undo mistakes, and follow along more effectively. It’s also a great way to share your code with others. Node and NPM Before we begin, you’ll need to install Node and NPM¹⁸. These tools help manage the libraries (Node packages) required throughout this book. These packages can range from small utilities to entire frameworks. We’ll use npm (Node Package Manager) to install them. To check if Node and npm are installed, run the following commands in your terminal: ¹²https://www.robinwieruch.de/what-is-an-api-javascript/ ¹³http://bit.ly/3OWCnan ¹⁴https://www.robinwieruch.de/developer-setup/ ¹⁵https://www.robinwieruch.de/mac-setup-web-development/ ¹⁶https://codesandbox.io ¹⁷https://www.robinwieruch.de/git-essential-commands/ ¹⁸https://nodejs.org/en/
Fundamentals of React 10 Command Line node --version *vXX.YY.ZZ npm --version *vXX.YY.ZZ If no version numbers appear, you’ll need to install Node and npm. If you already have them installed, ensure you’re using the latest version. If you’re new to npm or need a refresher, my npm crash course¹⁹ will get you up to speed. Exercises: • Optional: Read more about yarn²⁰ and pnpm²¹. Both can be used as a replacement for npm. However, I do not recommend using them as a beginner. This exercise should only make sure that you know about the alternatives. ¹⁹https://www.robinwieruch.de/npm-crash-course/ ²⁰https://yarnpkg.com/ ²¹https://pnpm.io/
Fundamentals of React 11 Setting up a React Project In The Road to React, we’ll use Vite²² to set up our React application. Vite–a French word meaning quick–is a modern build tool for contemporary web frameworks (e.g. React). It comes with sensible defaults (read: built-in configuration) while remaining highly extensible for specific use cases (e.g. SVGs, linting, TypeScript, server-side rendering). The core of Vite consists of: • A development server, which allows you to run your React application locally (read: develop- ment environment). • A bundler, which generates highly optimized files for production-ready deployment (read: production environment). For React beginners, the key benefit of Vite is that it enables you to focus solely on learning React without being distracted by complex tooling. This makes Vite the perfect partner for getting started with React. There are two ways to create a React project with Vite: • Using an online template²³ – You can choose either React (recommended for this book) or React with TypeScript (for advanced users, requiring manual type implementation). This option lets you work online without setting up a local environment. • Setting up Vite locally (recommended) – This method involves creating a React project with Vite on your local machine and working in your preferred IDE (e.g. VSCode). Since the online template works out of the box, we’ll focus on setting up Vite on your local machine in this section. In a previous section, you installed Node and npm. The latter allows you to install third-party dependencies (read: libraries, frameworks, etc.) from the command line. To get started, open your command line tool and navigate to the folder where you want to create your React project. Here’s a quick crash course on command-line navigation: • use pwd (on Windows: cd) to display the current folder • use ls (on Windows: dir) to display all folders and files in the current folder • use mkdir <folder_name> to create a folder • use cd <folder_name> to move into a folder • use cd .. to move outside of a folder After navigating to the folder where you want to create your React project, enter the following command. We’ll refer to this project as hacker-stories, but feel free to choose any name you like. ²²https://bit.ly/3BsG1TH ²³https://bit.ly/3RPAZWz
Fundamentals of React 12 Command Line npm create vite@latest hacker-stories -- --template react Optionally, you can choose a React + TypeScript project if you feel confident. Check Vite’s installation website for instructions on setting up a React + TypeScript project. This book includes a TypeScript section later; however, it does not provide step-by-step guidance on converting JavaScript to TypeScript. Instead, at the end of each section, you’ll find an alternative TypeScript implementation. Next, follow the command line instructions to navigate into the project folder, install all third-party dependencies, and run the project locally on your machine: Command Line cd hacker-stories npm install npm run dev The command linewill output a URLwhere your project is running in the browser. Open the browser, navigate to the provided URL, and verify that the React project is displayed correctly. Additionally, please check in your package.json file whether you are on the latest React version. At the time of writing, Vite comes with React 18, but there is already React 19 out there. If you want to use React 19, you can manually upgrade React in your project. Command Line npm install react@latest react-dom@latest If you are using React with TypeScript, you also need to update the React’s types: Command Line npm install --save-dev @types/react@latest @types/react-dom@latest We will continue developing this project in the next sections; however, for the remainder of this section, we will explore the project structure and scripts (e.g. npm run dev). Exercises: • Read more about how to start a React project²⁴. ²⁴https://www.robinwieruch.de/react-starter/
Fundamentals of React 13 Project Structure First, let’s open the application in an editor/IDE. If you’re using VSCode, simply type code . in the command line. The following folder structure (or a variation of it, depending on the Vite version) should be displayed: Project Structure hacker-stories/ --node_modules/ --public/ ----vite.svg --src/ ----assets/ ------react.svg ----App.css ----App.jsx ----index.css ----main.jsx --.gitignore --eslint.config.js --index.html --package-lock.json --package.json --README.md --vite.config.js This is a breakdown of the most important folders and files: • package.json: This file shows you a list of all third-party dependencies (read: node packages which are located in the node_modules/ folder) and other essential project configurations related to Node/npm. • package-lock.json: This file indicates npm how to break down (read: resolve) all node package versions and their internal third-party dependencies. We’ll not touch this file. • node_modules/: This folder contains all node packages that have been installed. Since we used Vite to create our React application, there are various node modules (e.g. React) already installed for us. We’ll not touch this folder. • .gitignore: This file indicates all folders and files that shouldn’t be added to your git repository when using git, as such files and folders should be located only on your local machine. The node_modules/ folder is one example. It is enough to share the package.json and package- lock.json files with other developers in the team, so they can install dependencies on their end with npm install without having to share the entire node_modules/ folder with everybody.
Fundamentals of React 14 • vite.config.js: A file to configure Vite. If you open it, you should see Vite’s React plugin showing up there. If you would be running Vite with another web framework, the other framework’s Vite plugin would show up. In the end, there are many more things that can optionally be set up here. • public/: This folder holds static assets for the project like a favicon²⁵ which is used for the browser tab’s thumbnail when starting the development server or building the project for production. • index.html: The HTML that is displayed in the browser when starting the project. If you open it, you shouldn’t see much content though. However, you should see a script tag which links to your source folder where all the React code is located to output HTML/CSS in the browser. In the beginning, everything you need is located in the src/ folder. The main focus is on the src/App.jsx file, where React components are implemented. This file will serve as the foundation for your application, but later on, you may want to split your React components into multiple files, with each file managing one or more components. We’ll get to that point eventually. Additionally, you’ll find a src/main.jsx file, which serves as the entry point to the React world. You’ll become more familiar with this file in later sections. There are also src/index.css and src/App.css files to style your overall application and components, both of which come with default styles when you open them. You’ll modify these later as well. ²⁵https://bit.ly/3QvRupG
Fundamentals of React 15 npm Scripts After you have learned about the folder and file structure of your React project, let’s go through the available commands. All your project-specific commands can be found in your package.json file under the scripts property. They may look similar to these depending on your Vite version: package.json "dev": "vite", "build": "vite build", "lint": "eslint .", "preview": "vite preview" These scripts are executed with the npm run <script> command in an IDE-integrated terminal or your standalone command line tool. The commands are as follows: Command Line # Runs the application locally for the browser npm run dev # Lint the application locally for code style errors npm run lint # Builds the application for production npm run build Another command from the previous npm scripts called preview can be used to run the production- ready build on your local machine for testing purposes. In order to make it work, you have to execute npm run build before running npm run preview. Essentially npm run dev and npm run preview (after npm run build) should give the identical output in the browser. However, the former is not optimized for production and should exclusively be used for the local development of the application. Exercises: • Read more about Vite²⁶. • Exercise npm scripts: – Start your React application with npm run dev on the command line and check it out in the browser. * Exit the command on the command line by pressing Control + C. ²⁶https://bit.ly/3BsG1TH
Comments 0
Loading comments...
Reply to Comment
Edit Comment