Building A GitHub API   App With ReactJS

Building A GitHub API App With ReactJS

ยท

3 min read

In this article, we are going to learn about how to build a GitHub App, with reactjs. React is an open-source JavaScript library used for building user interfaces, and is one of the most popular front-end frameworks.

Create A React App

You can create a react app by first installing nodejs on your computer and using a node package manager to install and create react app on your terminal.

using npm: ๐Ÿ‘‡

npx create-react-app app-name

Then navigate to the folder created:

cd app-name

Then you start up your react app after installing:

npm run start

After the react app has been created you can start up with the necessary components you need alongside the necessary route's path to needed.

Create a Component To Fetch From GitHub API

Now, we will write the logic to fetch from the GitHub API.

we will create some components called (Repository.js and Repos.js) and also create a react pagination.

import React,{useState,useEffect} from "react";
import ReactPaginate from "react-paginate";
import Repos from "../Repos";
import {Helmet} from 'react-helmet-async';

const Repositories = () => {

  const [repos, setRepos] = useState([]);
  const [repoPerPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);

  useEffect(() => {
    const fetchRepos = async () => {
      setLoading(true);
      const res = await fetch("https://api.github.com/users/Orezy01/repos");
      const data = await res.json();
      setRepos(data);
      setLoading(false);
    };
    fetchRepos();
  }, []);


  function handlePageClick({ selected: selectedPage }) {
    // console.log('selectedPage', selectedPage);
    setCurrentPage(selectedPage+1);
  }


  const indexOfLastRepo = currentPage * repoPerPage;
  const indexOfFirstRepo = indexOfLastRepo - repoPerPage;
  const currentRepos = repos.slice(indexOfFirstRepo, indexOfLastRepo);





  // Change page

  const paginate = (pageNumber) => setCurrentPage(pageNumber);
  return (
    <div>
      <Helmet>
      <title>Repositories</title>
      <meta name="description" content="Repositories"/>
      <link rel="canonical" href="/Repositories" />
      </Helmet>

      <h1>Repositories</h1>
      <div>
        <h1 className="main-title">Repositories</h1>
        <Repos repos={currentRepos} loading={loading} />

        <ReactPaginate
          previousLabel={"prev"}
          nextLabel={"next"}
          breakLabel={"..."}
          pageCount={5}
          containerClassName={"pagination justify-content-center"}
          pageClassName={"page-item"}
          pageLinkClassName={"page-link"}
          previousClassName={"page-item"}
          previousLinkClassName={"page-link"}
          nextClassName={"page-item"}
          nextLinkClassName={"page-link"}
          activeClassName={"active"}
          reposPerPage={repoPerPage}
          totalRepos={repos.length}
          paginate={paginate}
          onPageChange={handlePageClick}
        />
      </div>
    </div>
  );
};

export default Repositories;

To make use of the react pagination you have to install the dependency using npm and import it to the Repositories.js file

npm install react-paginate --save

Repo.js Component: ๐Ÿ‘‡

import React from 'react'
import "./EndResults.css";


 const Repos = ({repos, loading}) => {

    if(loading){
        return <h2>Loading...</h2>
    }
  return (
    <div className='repos main-src'>
      {repos.map((repoList) => (
         <div className="co-md-6 d-flex justify-content-center" key={repoList.id}>
         <div className="card m-2 cbl text center">
           <div className="card-body">
            <img className='my_avatar' src={repoList.owner.avatar_url} alt="profile_image" />
             <span className="card-number">ID: {repoList.id}</span> 
             <h5 className="card-title mb-4">Repository Name: n{repoList.full_name}</h5>
             <p className="card-text">Description: {repoList.description}</p>
             <button className="button-85" >
               {" "}
               <a href={repoList.html_url} className="link-btn" target="_blank" rel="noreferrer">
               {repoList.name}
               </a>
             </button>
           </div>
         </div>
       </div>
          ))}

    </div>


  )
}
export default Repos;

The Repo.js components accept two props which are "repos" and "loading".This should be implemented with a search bar and a search button, so when a username is being entered and the "search button" is being clicked it fetches for the user's repository.

Using Error Boundary

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods.

import React, { Component } from "react";

export class ErrorBoundary extends Component {
  constructor(props) {
    super(props);

    this.state = {
      hasError: true,
    };
  }
  static getDerivedStateFromError(error) {
    return { hasError: false };
  }

  render() {
    if (this.state.hasError)
      return (
        <div class="alert alert-danger">
          <strong>Error!!!</strong> ErrorBoundary Message In Action...Please
          Ignore This Message
        </div>
      );

    return this.props.children;
  }
}

export default ErrorBoundary;

Implementing Seo(Search Engine Optimization)

With SEO, you can increase your ranking on search engine results pages (SERPs) and ensure that your content is seen by the right people.

We have to install a "Helmet" dependency with our node package manager: ๐Ÿ‘‡

npm install react-helmet
ย