Part 1: How to Create a Book App with React.js - A Step-by-Step Tutorial
Tags: react, books, webdev, tutorial
Published: 2023-04-15 12:57:15

A book app enables users to read books on their electronic devices without physical copies. Popular examples include Kindle, iBooks, Google Play Books, and Goodreads. This React.js tutorial covers building a book app using a [ Book API data](https://developers.google.com/books)

## Prerequisites

1. Install[ node.js ](https://nodejs.org/en/)to support your development.
2. Build a strong foundation in [JavaScript](https://www.javascript.com/).
3. Learn basic[ React.js ](https://reactjs.org/tutorial/tutorial.html)concepts.
4. Know how to integrate Application Programming Interfaces (APIs) into your project.

By the end of the tutorial, you will have gained the skills to independently create a similar project.

## Setting up the local environment on your system

i. **In setting up the book app project folder:**

Right-click on the folder you want

![folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iujgwmhcy8zjq0qwdzsc.jpeg)

After you have created the folder

**There are two ways for it to open in your terminal:**

- Right-clicking: a pop-up comes out, or a list of items to click on.
- Type **cmd** to launch a command prompt window.

**Right-clicking**

![rightClick](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dt4q7hay9o00vso3txpg.jpeg)

**Typing cmd inside the folder**

![cmd](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pkkwlhe23u0dlxem0p9y.gif)

ii. **Terminal**

After opening your terminal, simply type `code . `to launch the Integrated Development Environment (IDE). If you're using Visual Studio Code as your IDE, this will promptly direct you to your project folder.

Typing` code .` by right-clicking on the folder

OR

Typing `code .` by typing **cmd** inside the folder

![code .](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zovryi2or4x8otje4a8w.gif)
iii. **Inside the directory of your project**

Create a react boilerplate using the create-react-app or vite tool; I prefer vite.

I recommend using Vite to create a React boilerplate, although Create React App is also a good option. The reason for my preference is that Vite is not only faster for development but also easier to configure. Additionally, Vite is more versatile than Create React App, supporting other front-end frameworks such as Svelte.

```
npx create-react-app ./ or npx create-vite@latest ./
// I am using ./ because I am inside the folder
```

./ creates the react boilerplate for you right inside the created folder.

iv. **Styling your app**

Tailwind CSS was used to style and design the layout for this project.

Install Tailwind CSS or another preferred framework in your terminal for styling your project.

To install TailwindCSS, go to their documentation and follow the guidelines of your chosen framework.

v. **Dependency**

For this project, the following dependencies were installed:

```
npm install react-loader-spinner --save, npm react-icons and npm install react-router-dom@6
```

vi. **Start the application with these commands**

```
npm run start or npm run dev
```

Use `npm run start (CRA)` or `npm run dev (VITE)` depending on how you created the React application.

Now we have our _local environment_ working on our laptop let's create the project

## Creating the project

i. Create a folder called components ( creating this component folder is optional and just for organization purposes) under the src directory. This folder should contain all the necessary files for the project.

![folder component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r4y0eo7vijwqg2iolqnx.png)
ii. Create a folder called img (creating this img folder is optional and just for organization purposes) under the src directory. This folder should contain all the necessary images for the project.

![ImageFolder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6sv2t0udubj9dfil6rc9.png)

iii. **Navigation Bar Creation**

This is to allow users to navigate between different pages in the web application; we will create a navigation bar using React Router.

To create a navigation menu:
Run the following command to install react-router-dom:

```
npm install react-router-dom@6
```
Wait for npm to download and install the package and its dependencies.

Once the installation is complete, you can start using react-router-dom in your project.

Create a `Navbar.jsx `and an `Home.jsx `inside the component folder.

**Navbar.jsx**

```
import React from 'react';

const Navbar = () => {
  return (
    <div>
      <div>
        <h1 className='lg:text-3xl'>CR📚💖</h1>
        <nav>
          <ul className='flex ml-5'>
            <li>
              <a href='/' className='mr-5 focus:text-black'>
                Home
              </a>
            </li>
            <li>
              <a href='/quotes' className='focus:text-black'>
                Quotes📔
              </a>
            </li>
          </ul>
        </nav>
      </div>
    </div>
  );
};

export default Navbar;
```
- import the file Navbar.jsx into the Home.jsx.

**Home.jsx**

```
import React, { useState } from 'react';
import Navbar from './Navbar';

const Home = () => {

  return (
    <>
      <Navbar />
    </>
  );
};

export default Home;
```

Render the `Home.jsx` file into the root file `App.jsx`, which is created by default, to see it in the browser.

Keep in mind that we have installed react-router-dom as a dependency. Therefore, the library component Routes and Route will be imported in App.jsx to facilitate navigation.

**App.jsx**

```
import React from 'react';
import Home from './components/Home';
import { Routes, Route } from 'react-router-dom';

const App = () => {
  return (
    <div>
      <Routes>
        <Route path='/' element={<Home />} />
      </Routes>
    </div>
  );
};

export default App;
```
To enhance navigation, we will wrap our application with `BrowserRouter`, which is imported from react-router-dom.

**Main.jsx**

```
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
import {BrowserRouter} from 'react-router-dom'

ReactDOM.createRoot(document.getElementById('root')).render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
)
```
**Result**

![nav](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/91air92bnutodt1ecewm.png)
iv. **Hero section**
Before we begin writing the hero section or landing page in the `Home.jsx` file, we'll need to import the **useState ()**, which will allow us to perform dynamic updates on the component in this project.

The input field that you see in the hero section was previously created in a separate file input.js and then imported, where it was placed under the paragraph tag to be displayed as part of the hero section.

**Home.jsx**

```
import React, { useState } from 'react';
import Navbar from './Navbar';
import Input from './Input';

const Home = () => {
  // The useState() is imported so we can dynamically change or update the heading when a book name is typed in the input field.
  const [term, setTerm] = useState('Anything');

  return (
    <div>
      <Navbar />
      <div className='header'>
        <div className='overlay'>
          <h2 className='Heading-text'>Books on {term}</h2>

          <p className='text-md mb-4 px-2 lg:px-0'>
            “Reading is an act of civilization; it’s one of the 
             greatest acts
             of civilization because it takes the free raw 
             material of the mind and builds castles of 
             possibilities.”
          </p>

          <Input />
        </div>
      </div>
    </div>
  );
};

export default Home;
```

**Input.jsx**

```
import React from 'react';

const Input = () => {
  const handleSubmit = (e) => {
    e.preventDefault();
    // Handle form submission here
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type='text'
          placeholder='type here...'
          autoComplete='off'
          className='input'
        />
        <button type='submit' className='btn'>
          search
        </button>
      </form>
    </div>
  );
};

export default Input;
```
**Result**
![hero](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bmqzh6tis6b34kb1x78f.png)
As previously mentioned, [TailwindCss ](https://tailwindcss.com/) was utilized to style this project.

## Fetching the data

Fetching data involves retrieving information from an external source, such as a web API, to populate and maintain a website's or web application's content. Two hooks, **useState()** and **useEffect()**, are imported to manage the application's state and re-render the API whenever there is a change. Data can be fetched from any file or component of a React project based on specific needs.

In this project, the `Home.jsx `component is used for data retrieval.

To fetch your data you can do it by following these steps:

i. Import the **useEffect()** and **useState()** from the react package, which we will use to fetch the API.

```

import React, {  useState, useEffect } from 'react';
```

ii. To store the API data, create a new state variable inside the `Home.jsx` functional component using the **useState()**.

```
const [books, setBooks] = useState([]);
```

iii. Wrap the **fetch()** function or any third-party library like **axios** inside the **useEffect()** to ensure that the API is only rendered once.

Here's an example of how to use the **fetch()** API.
```
useEffect(() => {
  fetch(`https://www.googleapis.com/books/v1/volumes q=${term}&key=${import.meta.env.VITE_SOME_VALUE}`)
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      setData(data.items);
    })
    .catch((err) => {
      setError(err.message);
    });
}, []);
```

This code will fetch data from the [Book](https://developers.google.com/books ) API and set it to the data state variable.

Upon retrieving the API using **fetch()**and obtaining the API key, I needed to conceal it before uploading it to Github (good practice). For this project, I used the template literal (``) format for the URL because my API key was stored in another file.

iv. **To hide your API key**

Create a `.env` file in the root of your application and store your key in that file.

**Example**

![env](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xywwazg57chbnc4an8yp.png)
A resource to guide you .env

## Conclusion

This guide shows how to build a book app with React.js, including retrieving book data from an API and project setup instructions. Following this tutorial will allow you to fetch data from the API. The next tutorial covers creating a template for the data set and logic used in the project.

You can find the source code in [my repository](https://github.com/ijayhub/Book-Web-App).

## Resource

Looking for an article on APIs to use in your projects? You may find it helpful to read through the following article:

- [Public APIs Developers Can Use in Their Projects.](https://ijaycent.hashnode.dev/public-apis-developers-can-use-in-their-projects)

This resource provides a range of APIs that are available for developers to use.

Thank you for reading 💖