Build 3 React Projects in 4 Hours | ReactJS Course For Beginners
By PedroTech
Key Concepts
- React Components: Building blocks of React applications, reusable UI elements.
- State Management: Managing data that changes over time within a component or across the application.
- Hooks: Functions that let you "hook into" React state and lifecycle features from function components (e.g.,
useState,useEffect,useRef,useContext). - Props: Data passed from a parent component to a child component.
- Event Handling: Responding to user interactions like clicks and input changes.
- Conditional Rendering: Displaying different UI elements based on certain conditions.
- Array Methods: JavaScript methods like
map,filter,find,reduceused for data manipulation. - React Router: A library for handling navigation and routing in React applications.
- Context API: A way to share data across the component tree without prop drilling.
- Local Storage: Browser API for storing key-value pairs persistently on the client-side.
- API Fetching: Retrieving data from external sources (APIs) using
fetch. - Asynchronous Operations: Handling operations that don't block the main thread (e.g., API calls) using
async/awaitand Promises. - Custom Hooks: Reusable logic extracted into custom functions starting with
use. - Recharts: A charting library for React.
useRef: A hook to access DOM elements or persist mutable values across renders.useParams: A hook from React Router to access route parameters.useNavigate: A hook from React Router to programmatically navigate between routes.
Project 1: Memory Card Game
This project focuses on teaching the fundamentals of React components and state management.
1. Project Setup:
- Utilized
npx create vitto initialize a React project with Vite as the bundler. - Selected React and JavaScript as the framework and language, respectively.
- Deleted unnecessary boilerplate files (
React SVG,assetsfolder,app.css,index.csscontent). - Pasted pre-written CSS into
index.cssto focus on React logic.
2. Core Components and Structure:
App.jsx: The main application component, acting as the container for other components.- Created a
divwith classapp. - Established a
componentsfolder for organizing UI elements.
- Created a
GameHeaderComponent: Displays the game title, score, moves, and a "New Game" button.- Receives
scoreandmovesas props fromApp.jsx. - Includes an
h1for the title and divs for stats. - Uses
spanelements to style individual text parts (e.g., "Score", "0").
- Receives
CardComponent: Represents an individual card in the game.- Receives
cardobject andonClickfunction as props. - Renders a
divwith classcard. - Includes
card-front(showing a question mark) andcard-back(showing the emoji). - Dynamically applies the
flippedclass based on thecard.isFlippedstate. - Applies the
matchedclass ifcard.isMatchedis true.
- Receives
3. Game Logic and State Management:
cardValuesArray: An array of emojis (e.g., fruits) to be used in the game. Each emoji is listed twice to create pairs.useStateHook:cards: An array of objects, each representing a card withid,value(emoji),isFlipped(boolean), andisMatched(boolean).flippedCards: An array to store the IDs of the two cards currently flipped.matchedCards: An array to store the IDs of cards that have been successfully matched.score: Tracks the number of matches.moves: Tracks the total number of card flips.isLocked: A boolean to prevent further clicks while cards are being revealed or matched.
useEffectHook:- Used to initialize the game by calling
initializeGamewhen the component mounts. - Used to manage the
isLockedstate and reset it after a delay.
- Used to initialize the game by calling
initializeGameFunction:- Shuffles the
cardValuesarray (initially uses the default order, shuffling is implemented later). - Creates an array of card objects, each with
id,value,isFlipped: false, andisMatched: false. - Updates the
cardsstate with this initialized array. - Resets
score,moves,matchedCards,flippedCards, andisLockedstates.
- Shuffles the
handleCardClickFunction:- Prevents clicks if the card is already flipped, matched, or if the game is locked.
- Updates the
isFlippedstate for the clicked card. - Adds the clicked card's ID to
flippedCards. - If two cards are flipped:
- Checks for a match based on
value. - If matched: Updates
isMatchedstate, adds IDs tomatchedCards, incrementsscore, and resetsflippedCards. - If not matched: Flips cards back after a delay, resets
flippedCards, and incrementsmoves.
- Checks for a match based on
- Updates
isLockedstate to prevent clicks during the flip-back process.
shuffleArrayFunction: Implements the Fisher-Yates (Knuth) shuffle algorithm to randomize the card order.winMessageComponent: Displays a congratulatory message and the number of moves upon game completion.- Conditionally rendered based on
isGameComplete(whenmatchedCards.lengthequals the total number of cards).
- Conditionally rendered based on
- Custom Hook (
useGameLogic):- Extracts all game logic (states, functions) into a separate hook for better organization.
- Takes
cardValuesas an argument. - Returns all necessary states and functions to the
Appcomponent.
4. Key Arguments/Perspectives:
- The importance of practical experience over endless tutorials for learning React.
- The benefit of breaking down complex UIs into smaller, manageable components.
- The power of state management (
useState) for handling dynamic data. - The utility of
useEffectfor managing side effects and component lifecycle. - The advantage of custom hooks for code organization and reusability.
Project 2: Music Player Website
This project focuses on state management, local storage, routing, and working with audio.
1. Project Setup:
- Initialized a React project using Vite.
- Deleted boilerplate files and pasted pre-written CSS.
- Created a
songsfolder containing audio files.
2. Core Components and Structure:
App.jsx: The main application component, responsible for routing and layout.- Uses
BrowserRouter,Routes, andRoutefromreact-router-domfor navigation. - Defines two routes:
/(for all songs) and/playlists(for playlists). - Includes a
Navbarcomponent. - Divides the main content into a
playersection and acontentsection.
- Uses
Navbar.jsx: Handles navigation links.- Uses
Linkcomponents fromreact-router-domfor internal navigation. - Dynamically applies an
activeclass based on the current route usinguseLocationhook. - Includes a brand logo/name.
- Uses
MusicPlayer.jsx: The UI for the music player controls (play/pause, next/previous, volume, progress bar).- Displays track information (title, artist).
- Includes a progress bar (
input type="range") and volume control. - Renders play/pause, next, and previous buttons.
- Uses
useRefto interact with the HTMLaudioelement.
AllSongs.jsx: Displays a list of all available songs.- Renders song cards with title, artist, and duration.
- Highlights the currently playing song.
- Allows users to select songs to play.
Playlists.jsx: Manages user-created playlists.- Allows creating new playlists.
- Displays existing playlists.
- Allows adding songs to playlists.
- Allows deleting playlists.
- Persists playlist data using local storage.
3. State Management and Logic (using Context API):
MusicContext: A global store for music-related data and functions.allSongs: An array of song objects, each withid,title,artist,url, andduration.currentTrack: The currently playing song object.currentTrackIndex: The index of the current track in theallSongsarray.isPlaying: Boolean indicating if the music is playing.currentTime: Current playback time in seconds.duration: Total duration of the current track in seconds.volume: Current volume level (0-1).playlists: An array of playlist objects, each containing anid,name, and an array ofsongs.selectedPlaylist: The playlist currently being interacted with.searchQuery: The text entered in the song search input.showDropdown: Boolean to control the visibility of the song search dropdown.- Functions:
handlePlaySong,nextTrack,previousTrack,play,pause,formatTime,handleTimeChange,handleVolumeChange,createPlaylist,deletePlaylist,addSongToPlaylist,handlePlayFromPlaylist.
useMusicCustom Hook: A convenient wrapper arounduseContext(MusicContext)to access music-related state and functions.useEffectHook:- Used extensively for:
- Loading initial song data.
- Managing audio playback (play/pause based on
isPlayingstate). - Updating
currentTimeanddurationbased on audio events (timeupdate,loadedmetadata). - Handling song end (
endedevent) to play the next track. - Persisting playlists to local storage.
- Loading playlists from local storage on component mount.
- Updating the audio element's source when the
currentTrackchanges.
- Used extensively for:
4. Key Features and Implementations:
- Routing: Implemented using
react-router-domfor navigation between "All Songs" and "Playlists" pages. - Audio Playback: Utilizes the HTML
audioelement anduseRefto control playback, volume, and progress. - Local Storage Persistence: Stores playlist data in the browser's local storage to maintain it across sessions.
- Dynamic UI: The UI (e.g., active song highlighting, play/pause button icon) updates based on the application's state.
- CRUD Operations for Playlists: Allows users to Create, Read, Update (add songs), and Delete playlists.
- Song Search and Filtering: Enables searching for songs to add to playlists, with filtering based on title and artist.
- Progress Bar and Volume Control: Interactive elements to control playback time and volume.
- Responsive Design: The UI adapts to different screen sizes.
5. Key Arguments/Perspectives:
- The importance of global state management (Context API) for sharing data across multiple components.
- The utility of local storage for client-side data persistence.
- The power of custom hooks for encapsulating reusable logic.
- The role of
useEffectin handling side effects and asynchronous operations. - The benefits of using libraries like React Router for navigation.
Project 3: Crypto Price Tracker
This project focuses on fetching data from an API, displaying real-time financial information, and creating interactive charts.
1. Project Setup:
- Initialized a React project using Vite.
- Deleted boilerplate files and pasted pre-written CSS into
index.css. - Created an
apifolder for API-related functions and autilsfolder for helper functions. - Installed
react-router-domfor routing andrechartsfor charting.
2. Core Components and Structure:
App.jsx: Sets up the application's routing structure.- Uses
BrowserRouter,Routes, andRoutefromreact-router-dom. - Defines two routes:
/(homepage for listing cryptocurrencies) and/coin/:id(detail page for a specific cryptocurrency). - Includes a
Navbarcomponent (though not explicitly detailed in the transcript for this project, it's implied by the final demo). - Includes a
Footercomponent.
- Uses
Pages/Home.jsx: Displays a list of cryptocurrencies.- Fetches cryptocurrency data from the CoinGecko API.
- Manages loading states and error handling.
- Allows users to switch between list and grid views.
- Provides filtering and sorting options (by name, price, 24-hour change, rank).
- Includes a search bar to filter cryptocurrencies by name or symbol.
- Renders
CryptoCardcomponents for each cryptocurrency.
Pages/CoinDetail.jsx: Displays detailed information about a specific cryptocurrency.- Fetches detailed data for a single coin using its ID from the URL parameters.
- Displays coin logo, name, symbol, rank, price, 24-hour change, market cap, volume, circulating supply, and total supply.
- Renders a price chart using Recharts for the last 7 days.
- Includes a "Go Back" button to return to the homepage.
Components/CryptoCard.jsx: Represents an individual cryptocurrency card on the homepage.- Displays coin logo, name, symbol, rank, price, 24-hour price change, and market cap/volume.
- Dynamically styles the price change based on whether it's positive or negative.
- Uses
Linkfromreact-router-domto navigate to theCoinDetailpage when clicked.
Components/Navbar.jsx(Implied): Handles navigation and search functionality.Components/Footer.jsx: Displays footer information.
3. API Integration and Data Fetching:
api/coinGecko.js: Contains functions for interacting with the CoinGecko API.fetchCryptos(): Fetches a list of cryptocurrencies (markets data) from the API.fetchCoinData(id): Fetches detailed data for a specific cryptocurrency by its ID.fetchChartData(id): Fetches historical price data for a specific cryptocurrency for charting.
fetchAPI: Used to make HTTP requests to the CoinGecko API.async/await: Used for handling asynchronous API calls.- Error Handling: Implemented using
try...catchblocks to handle potential API request failures. - Loading States:
useStateis used to manageisLoadingand display a loading spinner while data is being fetched.
4. Data Formatting and Utility Functions:
utils/formatter.js: Contains helper functions for data formatting.formatPrice(price): Formats currency values with appropriate decimal places and currency symbols.formatMarketCap(marketCap): Formats large numbers (trillions, billions) into human-readable strings.
5. Charting with Recharts:
rechartslibrary: Used to create interactive line charts.ResponsiveContainer: Makes the chart responsive to screen size changes.LineChart: The main chart component.CartesianGrid: Adds a dashed grid to the chart background.XAxisandYAxis: Define the axes of the chart.YAxisusesdomain="auto"to dynamically adjust the scale.
Line: Renders the actual line on the chart, with customizable stroke color and type.Tooltip: Displays information when hovering over data points on the chart.
6. Key Features and Implementations:
- Dynamic Routing: Uses route parameters (
:id) to fetch and display data for individual coins. - State Management:
useStateis used for managing crypto lists, individual coin data, loading states, view modes, sort orders, and search queries. - Conditional Rendering: Used to display loading states, error messages, or the actual data.
- List/Grid View Toggle: Allows users to switch between different display layouts for the cryptocurrency list.
- Filtering and Sorting: Implements functionality to sort and filter the cryptocurrency list based on various criteria.
- Search Functionality: Enables users to search for cryptocurrencies by name or symbol.
- Real-time Data (Simulated): Uses
setIntervalto periodically fetch updated cryptocurrency data, simulating real-time updates (with a note about potential rate limiting).
7. Key Arguments/Perspectives:
- The importance of using free and public APIs for learning and development.
- The value of dedicated charting libraries like Recharts for creating complex visualizations.
- The benefits of separating API logic and utility functions into dedicated modules.
- The effectiveness of React Router for managing navigation in single-page applications.
- The importance of responsive design for web applications.
Chat with this Video
AI-PoweredHi! I can answer questions about this video "Build 3 React Projects in 4 Hours | ReactJS Course For Beginners". What would you like to know?