Course Intro
00:00:00This ultimate React course covers everything from basics to advanced concepts, enabling you to build fast and scalable applications. You’ll create a production-grade app for discovering video games with features like dark/light mode toggling, game filtering by genre/platform, dynamic page title updates during filter changes, sorting options, and loading skeletons while fetching data. Advanced topics such as routing, state management, authentication, error handling and performance optimization will also be explored in depth. The instructor brings over 20 years of experience in software engineering and has successfully taught millions through various platforms.
Prerequisites
00:01:55To take this course, a solid understanding of HTML, CSS, and JavaScript is essential; prior knowledge of React isn't necessary. The course will utilize TypeScript, which enhances JavaScript by adding static typing to catch errors early in development. Even if you're unfamiliar with TypeScript, comprehensive guidance will be provided from the basics.
What is React?
00:02:43React is a JavaScript library designed for building dynamic and interactive user interfaces, created by Facebook in 2011. It simplifies the process of managing complex web applications by allowing developers to use reusable components instead of directly manipulating the Document Object Model (DOM). This modular approach enhances code organization and efficiency, making it easier to create responsive designs. For instance, a webpage can be constructed using separate components like navigation bars or game cards that work independently yet integrate seamlessly into one cohesive application.
Setting Up the Development Environment
00:04:57To build applications with React, ensure you have Node version 16 or higher. Check your current version by running 'node -v' in the command prompt; if it's lower than 16, download the latest from nodejs.org. Visual Studio Code (VS Code) is recommended as an editor for this course, but any preferred editor can be used. If using VS Code, install the Prettier extension to format code automatically upon saving files.
Creating a React App
00:06:24To create a React application, you can use either Create React App (CRA) or the increasingly popular Vite tool. To start with Vite, run 'npm create vite@latest' and specify version 4.1.0 for consistency in experience. After naming your project and selecting React as the framework along with TypeScript as the language, navigate to your project folder and install dependencies using 'npm install'. Open this project in VS Code by typing 'code .' or dragging it into VS Code; then launch an embedded terminal to run your web server with 'npm run dev', which will typically be accessible at localhost on port 5173.
Project Structure
00:09:17The project structure of a React application includes several key folders and files. The 'node_modules' folder contains third-party libraries, while the 'public' folder holds public assets like images and videos. The source code resides in the 'src' folder, which currently has an app component that will be rewritten from scratch. Additionally, there's an index.html file serving as a basic template with a root div for the application container and references to main.tsx as its entry point. Other important files include package.json detailing project dependencies (React version 18) and development tools, along with TypeScript configuration settings for compiling code.
Creating a React Component
00:11:20Creating Functional Components with JSX To create a React component, start by adding a new file named message.tsx in the source folder. Function-based components are preferred for their conciseness and ease of use over class components. When naming functions, follow Pascal casing conventions to ensure clarity within your codebase. The UI can be defined using JSX syntax which resembles HTML but is compiled into JavaScript under the hood.
Integrating Components and Dynamic Content After defining the Message component, export it as default and import it into another component like App to render it inside a div element. Always close your React components properly or face compilation errors; self-closing tags offer concise alternatives. With JSX, dynamic content can easily be created by embedding JavaScript expressions directly within braces—allowing for conditional rendering based on variable values.
How React Works
00:16:41React creates a component tree with the app as the root and child components beneath it. Upon starting, React builds a virtual DOM, an in-memory representation of this structure that allows for efficient updates when state changes occur. When data within a component alters, React modifies the corresponding node in the virtual DOM and compares it to its previous version to determine necessary updates before reflecting these changes in the actual DOM through react-dom library. The application dependencies are managed via package.json which includes both React and react-dom libraries; rendering occurs by targeting an HTML element identified as 'root'. Additionally, while primarily used for web applications via react-dom, React can also be utilized across platforms like mobile using libraries such as React Native.
React Ecosystem
00:19:00React is a JavaScript library designed for building dynamic and interactive user interfaces, distinguishing itself from frameworks like Angular and Vue. The key difference lies in their structure: libraries offer specific functionalities while frameworks provide comprehensive tools and guidelines for application development. Although React excels at UI creation, modern applications often require additional tools to handle routing, state management, internationalization, form validation, animations among others. Fortunately, React allows developers the flexibility to choose these supplementary tools based on project needs.
Building Components
00:21:04Building applications with React involves understanding fundamental concepts such as creating components, rendering markup using JSX, and managing state. It's crucial to learn how to pass input through props and effectively debug React applications. This foundational knowledge is essential for developing robust apps in React.
Creating a ListGroup Component
00:21:40Setting Up Bootstrap and Initial Component Creation To create a list group component, start by installing Bootstrap for styling. Open the terminal and run 'npm install bootstrap' version 5.2.3, then import it into your CSS file by replacing existing styles in main.tsx with 'import bootstrap/dist/css/bootstrap.css'. After confirming that Bootstrap is imported correctly in the browser, set up a new folder named components and create a file called ListGroup.tsx where you define a function returning an H1 element labeled "List Group".
Dynamic Item Display Using Bootstrapped Markup Next, enhance the ListGroup component to display items dynamically using markup from Bootstrap's documentation for list groups. Replace reserved JavaScript keywords like 'class' with 'className', utilizing multi-cursor editing for efficiency when renaming multiple instances at once. Ensure proper formatting of JSX code using Prettier as your default formatter to maintain readability; remember to wrap JSX markup in parentheses if not automatically formatted.
Fragments
00:27:15In React, a component can only return one element, which leads to errors when trying to add multiple elements like an H1. To resolve this issue, you can wrap the elements in a div or use fragments. While wrapping with a div adds unnecessary extra markup in the DOM for React's compliance, using fragments avoids this problem by not adding additional nodes. You can import Fragment from React and replace your divs with it; however, there's an even simpler syntax that allows you to use empty angle brackets instead of importing Fragment at all.
Rendering Lists
00:29:42To create a dynamic list in JSX, declare an array of items and use the map method to convert each item into a list element. Instead of using traditional loops, mapping allows for transforming data directly within JSX by wrapping expressions in curly braces. After implementing this code, ensure that each rendered item has a unique key prop to help React manage updates efficiently when items are added or removed from the list. In cases where there is no inherent ID available for uniqueness, such as with static strings like city names, you can utilize the string itself as the key.
Conditional Rendering
00:33:11Dynamic Content Display Based on Conditions Conditional rendering allows displaying different content based on specific conditions. For instance, if the item list is empty, a message like 'no items found' can be shown instead of an empty space. Using JSX expressions with ternary operators or logical AND simplifies this process and reduces code duplication by allowing dynamic rendering without cluttering the markup.
Streamlined Logic for Cleaner Code To enhance clarity in conditional logic within JSX, developers can extract complex conditions into separate variables or functions. This approach not only cleans up the main render but also enables passing parameters for varied messages depending on circumstances. A common technique involves using logical AND to return elements conditionally without needing null values when certain criteria are met.
Handling Events
00:38:36Implementing Click Event Handling in React Components To handle click events in a React component, each list item is assigned an onClick property that logs the clicked item's details to the console. By mapping over items and using their index as a second parameter, both the item value and its position can be displayed when clicked. The event object received during this process is of type SyntheticBaseEvent, which standardizes browser differences for handling events.
Best Practices for Structuring Event Handlers For more complex logic within event handlers, it's best practice to define separate functions rather than inline code. When declaring these functions with TypeScript, specifying types through annotations enhances auto-completion and type safety features. This allows developers to reference handler functions without invoking them directly while ensuring proper functionality upon user interaction.
Managing State
00:44:43Highlighting List Items with State Management To highlight a single item in a list, an 'active' CSS class is used. A variable called selectedIndex tracks the currently highlighted item's index, initialized to -1 for no selection. The active class is applied conditionally based on whether the current item's index matches selectedIndex. When clicking an item, this value should update accordingly; however, initially it doesn't work because it's locally scoped within the component.
Utilizing React Hooks for Dynamic State React's useState hook allows components to manage state that can change over time. By destructuring its return array into two elements—selectedIndex and setSelectedIndex—the component can track which item is selected dynamically upon user interaction. Each instance of a component maintains its own independent state; thus selections do not interfere across multiple instances of lists in the application.
Passing Data Via Props
00:50:44To create a reusable component for displaying lists, props (properties) are utilized to pass data into the component instead of hardcoding values. By defining an interface in TypeScript, we can specify that our component requires two properties: 'items' as an array and 'heading' as a string. This approach not only enhances reusability but also allows TypeScript to catch errors at compile time if these required props are missing when the component is used. The code becomes cleaner by destructuring these properties from the passed-in object rather than repeatedly using 'props.' Finally, dynamic rendering of headings based on input improves flexibility.
Passing Functions Via Props
00:54:42To create reusable components, it's essential to notify the parent component when an item is selected. Instead of embedding selection logic within the list group component, a function can be passed via props to handle this event in the app component. This function should accept a parameter representing the selected item and return void. By defining this prop as 'onSelectItem', we ensure that any action taken after selecting an item remains flexible and customizable for different applications.
State Vs Props
00:58:27Props are inputs passed to a component, while state is internal data that can change over time. Props should be treated as immutable or read-only, meaning they cannot be altered once set; changing them constitutes an anti-pattern in React. In contrast, state is mutable and designed for data that needs to update dynamically within the component. Both props and state trigger re-renders in React when changed.
Passing Children
01:00:00Dynamic Alert Component with Children Support Creating a component that accepts children enhances flexibility in rendering. By using the ES7 extension, developers can quickly generate React components without boilerplate code. The alert component is designed to display dynamic content by utilizing Bootstrap's styling and allows for text or HTML content to be passed as children instead of props.
Enhancing Usability through Type Adjustment To implement child support, rename the 'text' prop to 'children', enabling more versatile usage within JSX syntax. Adjusting TypeScript types from string to React node resolves issues when passing complex structures like HTML elements into the component. This approach streamlines how alerts are rendered while maintaining type safety and enhancing usability.
Inspecting Components with React Dev Tools
01:05:04React Dev Tools is an essential browser extension for inspecting React applications, available on Chrome, Firefox, and Microsoft Edge. After installation, users can access new tabs in the dev tools: Components and Profiler. The Components tab displays a hierarchy of components along with their props; for instance, it shows how the children prop contains various elements like strings or objects. Users can search for specific components easily within large applications and inspect corresponding DOM elements by selecting them directly from this interface.
Exercise: Building a Button Component
01:07:14Building Reusable Button Component with Dynamic Label Creating a Bootstrap button component involves using two classes: 'btn' as the base class and another for color, such as 'primary' or 'secondary'. The initial step is to encapsulate this markup in a reusable React component. After rendering a basic button, the next phase includes making its label dynamic by defining an interface for props that allows passing text through children.
Implementing Click Handling and Color Customization To enhance functionality, add an onClick prop to handle click events externally without compromising reusability. Implementing color customization requires adding a color prop that dynamically sets CSS classes based on input values like primary or secondary. To ensure type safety and prevent invalid colors from being used, leverage TypeScript's string literal types combined with union operators for supported bootstrap colors.
Exercise: Showing an Alert
01:14:15Creating Dismissible Alerts in React To create a dismissible alert in React, start by adding an alert component that is initially hidden. Use the state hook to manage its visibility with a boolean variable. When the button is clicked, set this variable to true, triggering a re-render and displaying the alert.
Implementing Close Functionality for Alerts Incorporate a close button within your alert using Bootstrap classes for styling. Implement functionality so that clicking this close button calls an external function passed as props from the parent component to update visibility back to false. This ensures proper rendering of components based on user interaction while maintaining clean code practices.