Build 3 React Projects in 4 Hours | ReactJS Course For Beginners

By PedroTech

Share:

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, reduce used 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/await and 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 vit to 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, assets folder, app.css, index.css content).
  • Pasted pre-written CSS into index.css to focus on React logic.

2. Core Components and Structure:

  • App.jsx: The main application component, acting as the container for other components.
    • Created a div with class app.
    • Established a components folder for organizing UI elements.
  • GameHeader Component: Displays the game title, score, moves, and a "New Game" button.
    • Receives score and moves as props from App.jsx.
    • Includes an h1 for the title and divs for stats.
    • Uses span elements to style individual text parts (e.g., "Score", "0").
  • Card Component: Represents an individual card in the game.
    • Receives card object and onClick function as props.
    • Renders a div with class card.
    • Includes card-front (showing a question mark) and card-back (showing the emoji).
    • Dynamically applies the flipped class based on the card.isFlipped state.
    • Applies the matched class if card.isMatched is true.

3. Game Logic and State Management:

  • cardValues Array: An array of emojis (e.g., fruits) to be used in the game. Each emoji is listed twice to create pairs.
  • useState Hook:
    • cards: An array of objects, each representing a card with id, value (emoji), isFlipped (boolean), and isMatched (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.
  • useEffect Hook:
    • Used to initialize the game by calling initializeGame when the component mounts.
    • Used to manage the isLocked state and reset it after a delay.
  • initializeGame Function:
    • Shuffles the cardValues array (initially uses the default order, shuffling is implemented later).
    • Creates an array of card objects, each with id, value, isFlipped: false, and isMatched: false.
    • Updates the cards state with this initialized array.
    • Resets score, moves, matchedCards, flippedCards, and isLocked states.
  • handleCardClick Function:
    • Prevents clicks if the card is already flipped, matched, or if the game is locked.
    • Updates the isFlipped state 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 isMatched state, adds IDs to matchedCards, increments score, and resets flippedCards.
      • If not matched: Flips cards back after a delay, resets flippedCards, and increments moves.
    • Updates isLocked state to prevent clicks during the flip-back process.
  • shuffleArray Function: Implements the Fisher-Yates (Knuth) shuffle algorithm to randomize the card order.
  • winMessage Component: Displays a congratulatory message and the number of moves upon game completion.
    • Conditionally rendered based on isGameComplete (when matchedCards.length equals the total number of cards).
  • Custom Hook (useGameLogic):
    • Extracts all game logic (states, functions) into a separate hook for better organization.
    • Takes cardValues as an argument.
    • Returns all necessary states and functions to the App component.

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 useEffect for 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 songs folder containing audio files.

2. Core Components and Structure:

  • App.jsx: The main application component, responsible for routing and layout.
    • Uses BrowserRouter, Routes, and Route from react-router-dom for navigation.
    • Defines two routes: / (for all songs) and /playlists (for playlists).
    • Includes a Navbar component.
    • Divides the main content into a player section and a content section.
  • Navbar.jsx: Handles navigation links.
    • Uses Link components from react-router-dom for internal navigation.
    • Dynamically applies an active class based on the current route using useLocation hook.
    • Includes a brand logo/name.
  • 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 useRef to interact with the HTML audio element.
  • 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 with id, title, artist, url, and duration.
    • currentTrack: The currently playing song object.
    • currentTrackIndex: The index of the current track in the allSongs array.
    • 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 an id, name, and an array of songs.
    • 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.
  • useMusic Custom Hook: A convenient wrapper around useContext(MusicContext) to access music-related state and functions.
  • useEffect Hook:
    • Used extensively for:
      • Loading initial song data.
      • Managing audio playback (play/pause based on isPlaying state).
      • Updating currentTime and duration based on audio events (timeupdate, loadedmetadata).
      • Handling song end (ended event) 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 currentTrack changes.

4. Key Features and Implementations:

  • Routing: Implemented using react-router-dom for navigation between "All Songs" and "Playlists" pages.
  • Audio Playback: Utilizes the HTML audio element and useRef to 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 useEffect in 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 api folder for API-related functions and a utils folder for helper functions.
  • Installed react-router-dom for routing and recharts for charting.

2. Core Components and Structure:

  • App.jsx: Sets up the application's routing structure.
    • Uses BrowserRouter, Routes, and Route from react-router-dom.
    • Defines two routes: / (homepage for listing cryptocurrencies) and /coin/:id (detail page for a specific cryptocurrency).
    • Includes a Navbar component (though not explicitly detailed in the transcript for this project, it's implied by the final demo).
    • Includes a Footer component.
  • 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 CryptoCard components 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 Link from react-router-dom to navigate to the CoinDetail page 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.
  • fetch API: Used to make HTTP requests to the CoinGecko API.
  • async/await: Used for handling asynchronous API calls.
  • Error Handling: Implemented using try...catch blocks to handle potential API request failures.
  • Loading States: useState is used to manage isLoading and 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:

  • recharts library: 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.
  • XAxis and YAxis: Define the axes of the chart.
    • YAxis uses domain="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: useState is 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 setInterval to 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-Powered

Hi! I can answer questions about this video "Build 3 React Projects in 4 Hours | ReactJS Course For Beginners". What would you like to know?

Chat is based on the transcript of this video and may not be 100% accurate.

Related Videos

Ready to summarize another video?

Summarize YouTube Video