In this post, I will show you how to create a dynamic table filled with API data. We are going to fetch some sample data, create the table and fill it with the data.
App structure
You can use create-react-app or online IDE to create the following file structure.
Fetch data with async … await
we are going to use async …await to fetch data from API asynchronously. You need an async function, especially, when you get data from an external source and must use in useEffect hook so that the dynamic portion will be rendered once the data is available.
Here, I use a sample API from https://sampleapis.com/. The API data is in JSON format. It returns an array of objects with some sample data on various countries in the world.
useEffect(() => {
const fetchData = async () => {
const response = await fetch(
'https://api.sampleapis.com/countries/countries');
const data = await response.json();
}
// Call the function
fetchData();
}, []);
App.js
In our App.js, there is a table filled with dynamic data fetching from the API. We use React state to hold the dynamic portion of the table. Then, we traverse the array of objects in the state and display the data in a table row.
The API returns about 250 countries, however, we are going to use only three countries.
import { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
const [ countries, setCountries ] = useState([]);
useEffect(() => {
const fetchata = async () => {
const response = await fetch(
'https://api.sampleapis.com/countries/countries');
const data = await response.json();
//use only 3 sample data
setCountries( data.slice( 0,3) )
}
// Call the function
fetchata();
}, []);
return (
<div className="App">
<h1>List of Countries</h1>
<table>
<thead>
<tr>
<th>country</th>
<th>capital</th>
<th>flag</th>
</tr>
</thead>
<tbody>
{
countries.map( (country,key) =>
<tr key={key}>
<td className='table-data'>{country.name }</td>
<td className='table-data'>{country.capital }</td>
<td className='table-data'><img width='20px' height='10px'
src={ country.media.flag } alt="flag" /></td>
</tr>
)
}
</tbody>
</table>
</div>
);
}
Add styles
Finally, you may add some CSS code to styles.css
.App {
font-family: sans-serif;
text-align: center;
}
table{
margin: 0 auto;
}
th{
background-color: rgb(68, 109, 109);
padding:5px 20px;
color:whitesmoke
}
.table-data {
text-align: center;
padding: 5px 10px;
background-color:rgb(206, 229, 236)
}