ReactJS-The Beginner Master Class
  • React In the Beginning
    • Lesson 1 - Demo: Build a Simple React App - Fast
    • Lesson 2 - HTML Review
    • Lesson 3 - CSS Review
    • Lesson 4 - Modern JavaScript (JSX) Patterns
    • Lesson 5 - Set up Dev Environment
    • Hands-on Practice
  • React Fundamentals
    • Lesson 1 - Understanding Old vs New Way of Building Web Apps - SPAs
    • Lesson 2 - Motivation for Using React as the Solution to Vanilla JS
    • Lesson 3 - What is ReactJS - How it Works
    • React Code Along from Scratch
    • Lesson 4 - Create and Run a React Project with Vite - Full Overview
    • Lesson 5 - Create Hook by State Management in React
    • Lesson 6 - React Project File and Folder Walkthrough
    • Lesson 7 - JSX and How React Treats the DOM & JSX Compilation(by Babeljs) - Overview
    • Lesson 8 - Understanding the Main Files - App.jsx and main.jsx
    • Lesson 9 - Props and One-Way Data Flow - Overview
    • Lesson 10 - Google Bookshelf App - Ver 1.0
    • Hands-on Practice I
    • Hands-on Practice II
  • React State and Styling
    • Lesson 1 - Pulling Book Data from a Different Data File
    • Lesson 2 - Overview of How State Works in React
    • Lesson 3 - RandomQuote App
    • Lesson 4 - Lifting State Up - React Pattern Overview
    • Hands-On - Simple Counter
  • Forms and Interactivity - Grocery List App
    • Lesson 1 - Setup a Simple Form and Input
    • Lesson 2 - Build Form Profile App Using Multi-input Form Data
    • Hands-on : Build a Grocery List App
  • Connecting to the Backend - Consuming APIs - UseEffect Hook
    • Lesson 1 - Connecting to the Back End - Understanding Side Effects, Hooks and useEffect - Overview
    • Lesson 2 - Fetching Data from the Backend the Right Way with useEffect Hook
    • Lesson 3 - Setting Up Loading State
    • Hands-on :Use Dependency Array and Adding Values that Control Side Effects
  • Solo Project 1
  • RESTful APIs :Build a BookSearch App -Ver 2.0
    • Lesson 1: Build and test RESTful APIs with Postman
    • Lesson 2 - BookShelf App Structure
    • Lesson 3 - Create NavBar.jsx Component
    • Lesson 4 - Create Footer Component
    • Lesson 5 - Create BookList.jsx Component
    • Lesson 6 - Create BookCard.jsx Component
    • Lesson 7 - Creating Custom Hooks - useBooks and api-client
    • Lesson 8 - Controlling Network Activities in React with AbortController
    • Lesson 9 - Show Book Details in a Modal - Working
    • Lesson 10 - Bookshelf App Summary
  • Multi-Page Applications (MPAs)
    • Build a Multi-Page React Application
    • Multi-Page React Application
    • Hands-on Practice
  • Backend Frameworks-NEXT.JS
    • Migrating from React to Next.js
    • Lesson 1: Key Concepts of NodeJS and Express for Backend Web Development
    • Lesson 2: How to set up a new Next.js project
    • Lesson 3: How to create Layouts and Pages
    • Hands-on Practice 1
    • Hands on Practice 2
      • New Project & Folder Structure
      • File-Based Routing
      • Server vs Client Components & Router Hooks
      • Start On The Navbar
      • Navbar Links, Dropdowns & React Icons
      • Active Links & Conditional Rendering
      • Homepage Components
      • Properties Page
      • Property Card Dynamic Data
      • Home Property Listings
      • Custom Not Found & Loading Pages
  • Git and GitHubs
    • Git Installation
    • Git Commands
    • GitHub Repository
    • Hands-on Practice
  • Database in Application
    • React Supabase CRUD
    • Hands-on: Note Taking App
  • NoSQL Database
    • Installing MongoDB Community Edition
    • System Env Path Setting
    • How to use MongoDB Shell
    • How to Connect and Use Mongosh in VS Code via MongoDB Extension
    • MongoDB Guide
  • Solo Project 2
  • Deployment and Web Hosting
    • Lesson 1. React+Vite+TS+Shadcn Project
    • Lesson 2. Deploying a React Vite App to Vercel from Vercel CLI
    • Lesson 3 Connecting to GitHub Repo and Automate Deployment
  • Solo Project 3
  • Final Term Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 2 Team Project
    • Level 2 Team Project
    • Level 3 Team Project
    • Level 3 Team Project
Powered by GitBook
On this page
  • Google BookShelf React App v1
  • App Structure
  • The code for the AppBookShelf.jsx parent component
  • Explanation of AppBookShelf.jsx Code Structure and Snippets
  • Outcome
  1. RESTful APIs :Build a BookSearch App -Ver 2.0

Lesson 2 - BookShelf App Structure

PreviousLesson 1: Build and test RESTful APIs with PostmanNextLesson 3 - Create NavBar.jsx Component

Last updated 21 days ago

Google BookShelf React App v1

App Structure

We are going to build Google Bookshelf React App with the following components:

Parent component : AppBookShelf.jsx contains three child components – NavBar.jsx, BookList.jsx and Footer.jsx. The children components are put in components folder.

Child components in components folder :

  1. NavBar.jsx: This component includes the application header title and the SearchBar.jsx, both located in the same directory.

  2. BookList.jsx: This component is responsible for displaying a list of book information fetched from an API endpoint. It accepts props for the title, authors, description, and publisher, as well as additional query props.

  3. Footer.jsx: Contains copyright information along with social media links for Instagram, YouTube, Facebook, and X.

The code for the AppBookShelf.jsx parent component

Step-by-Step Explanation for Students

  1. Setup:

    • Import the required libraries and components.

    • Initialize the state variables using useState.

  2. Fetch API Data:

    • Define fetchBooks to fetch and parse data from the Google Books API.

    • Handle errors gracefully.

  3. React Lifecycle:

    • Use useEffect to ensure the API is called when the component loads or when query changes.

  4. Handle User Input:

    • Define a function (handleSearch) to update the query based on user input.

  5. Render the UI:

    • Divide the app into child components (NavBar, BookList, Footer) for better modularity.

    • Pass props to child components to maintain communication between them.

  6. Layout Structure of AppBookShelf Component

// Layout Design of AppBookShelf Component
AppBookShelf Component
│
├── State
│   ├── books (useState) - Array of fetched books
│   └── query (useState) - Search query string, default: 'react'
│
├── Methods
│   ├── fetchBooks() - Async function to fetch books from Google Books API
│   └── handleSearch() - Updates query state with new search term
│
├── Effects
│   └── useEffect - Calls fetchBooks when query changes
│
└── Render Structure
    └── <div> (container mt-5)
        ├── <NavBar> - Navigation component
        │   ├── Props:
        │   │   ├── query - Current search query
        │   │   └── onSearch - handleSearch callback
        │
        ├── <BookList> - Book display component
        │   ├── Props:
        │   │   ├── books - Array of book data
        │   │   └── query - Current search query
        │
        └── <Footer> - Footer component
//Pareant component in src folder : AppBookShelf.jsx
// Import necessary libraries and hooks
import React, { useState, useEffect } from 'react';
import NavBar from './components/NavBar';
import BookList from './components/BookList';
import Footer from './components/Footer';
import 'bootstrap/dist/css/bootstrap.min.css';

const AppBookShelf = () => {
  // Step 1: Initialize state variables
  const [books, setBooks] = useState([]); // Stores fetched book data
  const [query, setQuery] = useState('react'); // Default query for API

  // Step 2: Fetch books from the API
  const fetchBooks = async () => {
    try {
      const response = await fetch(`https://www.googleapis.com/books/v1/volumes?q=${query}`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      setBooks(data.items || []); // Update state with fetched books or an empty array
    } catch (error) {
      console.error('Error fetching books:', error);
    }
  };

  // Step 3: Use useEffect to trigger fetchBooks on mount or query change
  useEffect(() => {
    fetchBooks();
  }, [query]);

  // Step 4: Handle query updates from child components
  const handleSearch = (newQuery) => {
    setQuery(newQuery);
  };

  return (
    <div className="container mt-5">
      {/* Step 5: Render the NavBar with props */}
      <NavBar query={query} onSearch={handleSearch} />

      {/* Step 6: Render the BookList with fetched data and query */}
      <BookList books={books} query={query} />

      {/* Step 7: Render the Footer */}
      <Footer />
    </div>
  );
};

export default AppBookShelf;

Explanation of Code Structure

App Structure

API End Point: https://www.googleapis.com/books/v1/volumes?q=${query}

  1. Import Libraries and Components:

    • React: Core library for building UI.

    • useState and useEffect: Hooks for managing state and side effects.

    • Child Components: NavBar, BookList, and Footer for modularity.

  2. State Management:

    • books: Holds the book data fetched from the API.

    • query: Stores the user's search term.

  3. Fetching Data:

    • fetchBooks is an asynchronous function that retrieves book data from the Google Books API.

    • Updates the books state with the fetched results or an empty array if no data is returned.

  4. Effect Hook:

    • Ensures fetchBooks runs when the component mounts or the query state changes.

  5. Handle Search:

    • handleSearch is a function that updates the query based on user input received from the NavBar component.

  6. Child Components:

    • NavBar: Contains the search bar and passes the query handling logic.

    • BookList: Receives books and query as props and displays book data.

    • Footer: Displays copyright and social media links.

  7. Bootstrap Integration:

    • Styling is done using Bootstrap classes for a professional look.

Explanation of AppBookShelf.jsx Code Structure and Snippets

The code is structured step-by-step to make it easy for students to understand how the parent component manages data and communicates with its child components. Here's a detailed breakdown:


1. Importing Libraries and Components

import React, { useState, useEffect } from 'react';
import NavBar from './components/NavBar';
import BookList from './components/BookList';
import Footer from './components/Footer';
import 'bootstrap/dist/css/bootstrap.min.css';
  • React: Core library for creating React components.

  • useState and useEffect: Hooks for managing state and side effects.

  • Child Components:

    • NavBar: Contains the search bar and header.

    • BookList: Displays the list of books.

    • Footer: Contains footer content (e.g., copyright and social links).

  • Bootstrap: A CSS framework for styling the app.


2. State Management

const [books, setBooks] = useState([]); // Stores the fetched book data
const [query, setQuery] = useState('react'); // Default search query
  • books:

    • Stores the array of books fetched from the API.

    • Initially set to an empty array.

  • query:

    • Stores the search term entered by the user.

    • Defaults to "react" to show results when the app first loads.


3. Fetching Data from the API End Point

const fetchBooks = async () => {
  try {
    const response = await fetch(`https://www.googleapis.com/books/v1/volumes?q=${query}`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    setBooks(data.items || []); // Update books state with fetched data
  } catch (error) {
    console.error('Error fetching books:', error);
  }
};
  • API Endpoint:

    • Fetches book data using the search term stored in query.

  • Steps:

    1. Makes an HTTP GET request using fetch.

    2. Checks if the response is successful (response.ok).

    3. Parses the response JSON and updates the books state.

    4. Handles errors with try...catch.


4. Using useEffect for Side Effects

useEffect(() => {
  fetchBooks();
}, [query]);
  • Purpose:

    • Automatically fetches data when the component mounts or when the query state changes.

  • Dependency Array:

    • [query] ensures the function re-runs only when the search term changes.


5. Handling Search Input

const handleSearch = (newQuery) => {
  setQuery(newQuery); // Updates the query state with the new input
};
  • Functionality:

    • Called back when the user enters a new search term.

    • Updates the query state, which triggers useEffect to fetch new data.


6. Rendering the Component - NavBar, BookList, Footer components

return (
  <div className="container mt-5">
    <NavBar query={query} onSearch={handleSearch} />
    <BookList books={books} query={query} />
    <Footer />
  </div>
);
  • Container: The entire app is wrapped in a Bootstrap container for layout.

  • Child Components:

    1. NavBar:

      • Receives query and handleSearch as props.

      • Displays the header and search bar.

    2. BookList:

      • Receives books and query as props.

      • Dynamically displays the list of books fetched from the API.

    3. Footer:

      • Displays footer content like copyright and social media links.



Bootstrap Integration

  • Classes:

    • container: Ensures a responsive layout.

    • mt-5: Adds top margin for spacing.

  • Provides a clean and professional look without writing custom CSS.


Outcome

By following these steps:

  1. Students can understand how to manage data and user interactions in a React app.

  2. They learn how to fetch, manage, and display data from an external API.

  3. They gain insight into component-based architecture and modular design.