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
Prerequisites
- Install node.js to support your development.
- Build a strong foundation in JavaScript.
- Learn basic React.js concepts.
- 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
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
Typing cmd inside the folder
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.
Typingcode .
by right-clicking on the folder
OR
Typing code .
by typing cmd inside the folder
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.
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.
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
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
As previously mentioned, TailwindCss 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 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
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.
Resource
Looking for an article on APIs to use in your projects? You may find it helpful to read through the following article:
This resource provides a range of APIs that are available for developers to use.
Thank you for reading đź’–
Top comments (0)