Create an API-based frontend project using React, Axios, and Ant design
Introduction
This article will guide you to create an application where we will use already-built APIs to create an application. Hence, we will not be worrying about creating the backend or the database, as the API takes care of that.
Prerequisites:
Knowledge of HTML, CSS, JavaScript, TypeScript (optional), React
Setting up the application
Create a directory named rick-and-morty-api
mkdir rick-and-morty-api
Navigate to the created directory:
cd rick-and-morty-api
Open the directory in Visual Studio Code, using the command: “code .”
code .
In the visual studio code, open the terminal and type the following command:
yarn create vite
You can notice we are using “yarn ”instead of “npm ”and “vite” instead of “create-react-app”. If you are using npm and create-react-app for a while this might be a good way to upgrade your skillset in creating frontend applications, as the yarn is widely used in large-scale projects, and vite is a popular alternative to create-react-app. This is because vite lets you create and run react applications.
Next, enter the project name and then navigate and choose react from the prompt as shown below:
We will be using TypeScript for this project, so choose TypeScript:
Now, as hinted by vite in the terminal, enter the three commands:
cd rick-and-morty-api
yarn
yarn dev
And there you go, if you are a user of “create-react-app”, you must have noticed the significant difference in the time taken to set up the app using vite (only 140 seconds):
Writing the command yarn dev will initialize the app and run on a port:
Install antd (ant design), Axios, react-router-dom, and styled-components by entering the following command in the terminal:
Yarn performs parallel installation resulting in better speed and performance compared to npm
yarn add antd axios react-router-dom styled-components
Remove all the boiler plate code in the app.css, app.tsx, and index.tsx
And add the following code to these files:
App.tsx
import "./App.css";
import Navbar from "../src/components/Navbar";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Characters from "./pages/Characters";
function App() {
return (
<>
<BrowserRouter>
<Navbar />
<Routes>
<Route path="/characters" element={<Characters />} />
</Routes>
</BrowserRouter>
</>
);
}
export default App;
index.css
* {
box-sizing: border-box;
font-family: sans-serif;
margin: 0;
}
Fetching the API and extracting data using axios
Create a new directory, “axios” in the src folder, src/axios
Subsequently, create a new file named “axios.tsx” and enter the following code:
import axios from "axios";
export const fetchData = async (endpoint: string) => {
try {
const { data } = await axios.get(`https://rickandmortyapi.com/api/${endpoint}`);
return data.results;
} catch (err) {
console.error(err);
}
};
Create a components directory in the src folder, src/components
Then, create the following files and insert the following code
Navbar:
import React, { useState } from "react";
import type { MenuProps } from "antd";
import { Menu } from "antd";
const items: MenuProps["items"] = [
{
label: <a href="/characters">Characters</a>,
key: "characters",
},
{
label: <a href="/locations">Locations</a>,
key: "locations",
},
{
label: <a href="/episodes">Episodes</a>,
key: "episodes",
},
];
const Navbar: React.FC = () => {
const [current, setCurrent] = useState("mail");
const onClick: MenuProps["onClick"] = (e: any) => {
console.log("click ", e);
setCurrent(e.key);
};
return (
<Menu
onClick={onClick}
selectedKeys={[current]}
mode="horizontal"
items={items}
/>
);
};
export default Navbar;
Create a new directory called pages, create a file named Characters and write the following code:
Characters.tsx
import { useState, useEffect } from "react";
import { fetchData } from "../axios/axios";
import styled from "styled-components";
import { Card } from "antd";
const Characters = () => {
interface ICharacter {
name: string;
status: string;
species: string;
image: string;
}
const endpoint: string = `character`;
const [characters, setCharacters] = useState<ICharacter[]>([]);
useEffect(() => {
const fetchCharacters = async () => {
const characters = (await fetchData(endpoint)) as ICharacter[];
setCharacters(characters);
};
fetchCharacters();
}, []);
const Container = styled.main`
background-color: #f0f2f5;
`;
const Header = styled.h1`
width: 91%;
margin: 0 auto;
padding-top: 3rem;
`;
const Wrapper = styled.div`
display: flex;
justify-content: center;
padding: 1rem;
flex-wrap: wrap;
width: 100%;
background-color: #f0f2f5;
`;
const CardWrapper = styled(Card)`
margin: 2rem;
`;
const ImageContainer = styled.div`
margin: 0 auto;
`;
return (
<Container>
<Header>Characters</Header>
<Wrapper>
{characters.map((character) => {
const { name, status, species, image } = character;
return (
<CardWrapper title={name} bordered={false} style={{ width: 300 }}>
<ImageContainer>
<img src={image} alt="image of character" width={200} />
</ImageContainer>
<div>Status: {status}</div>
<div>Species: {species}</div>
</CardWrapper>
);
})}
</Wrapper>
</Container>
);
};
export default Characters;
The development is complete, now you have a frontend application that fetched data from a pre-built API hosted on the web and displays content according to your style. It should look something like this:
Conclusion
I hope you learned how to fetch and extract data from an API using react. There are tons of free APIs that are already hosted on the web, you can use this method to fetch and display data from them as well.
Some of my recommendations are:
Star wars API: https://swapi.dev/
Openweather API: https://openweathermap.org/api
Challenge
There are two other APIs provided by the rickandmortyapi.com:
"locations": "https://rickandmortyapi.com/api/location"
"episodes": "https://rickandmortyapi.com/api/episode"
You can use these to complete your application by fetching the location and episode data. Take reference from the Characters.tsx page if you need it.