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
  • Creating Book Component and Pulling Book Data from data.js
  • Step-by-Step Procedure to Create the React Components and Use booksData
  • Final Project Structure
  1. React State and Styling

Lesson 1 - Pulling Book Data from a Different Data File

Creating Book Component and Pulling Book Data from data.js

Step-by-Step Procedure to Create the React Components and Use booksData


Final Project Structure

components
  ├── Book.jsx
  ├── data.js
App.jsx
index.js

1. Create the File Structure

  1. Inside the components folder, ensure you have the following files:

    • Book.jsx for the child component.

    • data.js (already provided).

  2. Inside src folder

    • App.jsx for the parent component.

data.js
// data.js
/** @format */

const booksData = {
  items: [
    {
      volume: {
        title: "Effective Java",
        subtitle: "Programming Language Guide",
        authors: ["Joshua Bloch"],
        description:
          "From the source of Java's design, this guide provides the best practices and expert insights for professional Java developers. Ideal for enhancing coding efficiency and understanding Java's capabilities.",
        image:
          "http://books.google.com/books/content?id=ka2VUBqHiWkC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api",
      },
    },
    {
      volume: {
        title: "Clean Code",
        subtitle: "A Handbook of Agile Software Craftsmanship",
        authors: ["Robert C. Martin"],
        description:
          "A must-read for developers striving to write clean code that enhances readability and maintainability. Includes practical advice and real-world examples from software engineering.",
        image:
          "http://books.google.com/books/content?id=_i6bDeoCQzsC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api",
      },
    },
    {
      volume: {
        title: "Head First Java",
        subtitle: "A Brain-Friendly Guide",
        authors: ["Kathy Sierra", "Bert Bates"],
        description:
          "An engaging, visually-rich approach to learning Java, suitable for beginners who want a complete understanding of object-oriented programming and Java basics.",
        image:
          "http://books.google.com/books/content?id=lXEBwv0LYogC&printsec=frontcover&img=1&zoom=5&source=gbs_api",
      },
    },
    {
      volume: {
        title: "Eloquent JavaScript, 3rd Edition",
        subtitle: "A Modern Introduction to Programming",
        authors: ["Marijn Haverbeke"],
        description:
          "Completely revised and updated, this best-selling introduction to programming in JavaScript focuses on writing real applications.",
        image:
          "http://books.google.com/books/content?id=FSVTDwAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api",
      },
    },
    {
      volume: {
        title: "Professional Java for Web Applications",
        subtitle: "Comprehensive Guide to Spring Framework",
        authors: ["Nicholas S. Williams"],
        description:
          "The comprehensive Wrox guide for creating Java web applications for the enterprise This guide shows Java software developers and software engineers how to build complex web applications in an enterprise environment.",
        image:
          "http://books.google.com/books/content?id=cHr0AgAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api",
      },
    },
  ],
};
export default booksData;

2. Create the Book.jsx Child Component

In BookList.jsx, define the functional component with props and state management:

// Some code
BookList (Component)
├── div (HTML element - className="card mb-3", style={...})
│   ├── div (HTML element - className="row g-0")
│   │   ├── div (HTML element - className="col-md-4")
│   │   │   └── img (HTML element - src=image, className="img-fluid rounded-start", alt=title)
│   │   └── div (HTML element - className="col-md-8")
│   │       └── div (HTML element - className="card-body")
│   │           ├── h5 (HTML element - className="card-title", text=title)
│   │           ├── h6 (HTML element - className="card-subtitle mb-2 text-muted", text=subtitle)
│   │           ├── p (HTML element - className="card-text")
│   │           │   ├── strong (HTML element - text="Author:")
│   │           │   └── text=author
│   │           ├── p (HTML element - className="card-text", text=description)
│   │           └── button (HTML element - className=dynamic, onClick=toggleReadStatus, text=dynamic)
import React, { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";

const BookList = ({ title, subtitle, author, description, image }) => {
  const [isRead, setIsRead] = useState(false);

  const toggleReadStatus = () => {
    setIsRead(!isRead);
  };

  return (
    <div className="card mb-3" style={{ maxWidth: "540px" }}>
      <div className="row g-0">
        <div className="col-md-4">
          <img src={image} className="img-fluid rounded-start" alt={title} />
        </div>
        <div className="col-md-8">
          <div className="card-body">
            <h5 className="card-title">{title}</h5>
            <h6 className="card-subtitle mb-2 text-muted">{subtitle}</h6>
            <p className="card-text"><strong>Author:</strong> {author}</p>
            <p className="card-text">{description}</p>
            <button
              className={`btn ${isRead ? "btn-success" : "btn-primary"}`}
              onClick={toggleReadStatus}
            >
              {isRead ? "Mark as Read" : "Mark as Unread"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default BookList;

3. Import and Use booksData in AppBookShelf.jsx

In AppBookShelf.jsx, pull the booksData from data.js, map over it, and render the Book components.

// AppBookShelf.jsx layout
pp (Component)
├── div (className="container mt-4")
│   ├── h1 (className="mb-4", text="Book List")
│   └── div (className="row")
│       └── map (booksData.items.map(...))
│           ├── div (className="col-md-6", key="0")
│           │   └── Book (Component)
│           │       ├── ... (props: title, subtitle, author, description, image)
│           ├── div (className="col-md-6", key="1")
│           │   └── Book (Component)
│           │       ├── ... (props: title, subtitle, author, description, image)
│           ├── ... (more div/Book components based on booksData.items)
import React from "react";
import Book from "./components/Book.jsx";
import booksData from "./components/data.js";
import "bootstrap/dist/css/bootstrap.min.css";

const App = () => {
  return (
    <div className="container mt-4">
      <h1 className="mb-4">Book List</h1>
      <div className="row">
        {booksData.items.map((book, index) => (
          <div className="col-md-6" key={index}>
            <BookList
              title={book.volume.title}
              subtitle={book.volume.subtitle}
              author={book.volume.authors.join(", ")}
              description={book.volume.description}
              image={book.volume.image}
            />
          </div>
        ))}
      </div>
    </div>
  );
};

export default App;

4. Install and Add Bootstrap Styling

Install Bootstrap via npm if not already installed:

npm install bootstrap

Make sure to import Bootstrap CSS in main.jsx or globally:

import "bootstrap/dist/css/bootstrap.min.css";

5. Run the Application

  1. Start the development server:

    npm run dev
  2. The application will display a styled book list where you can toggle the "read" status for each book.



This setup ensures a reusable Book component and a clean data flow from data.js to App.jsx.

PreviousReact State and StylingNextLesson 2 - Overview of How State Works in React

Last updated 2 months ago