Skip to content

Instantly share code, notes, and snippets.

@josecarneiro
Created June 4, 2022 10:56
Show Gist options
  • Save josecarneiro/1d341023b74a61cfe8b3422a953b1d43 to your computer and use it in GitHub Desktop.
Save josecarneiro/1d341023b74a61cfe8b3422a953b1d43 to your computer and use it in GitHub Desktop.
lab-wiki-countries proposed solution
import { useState, useEffect } from 'react';
import CountriesList from './components/CountriesList';
import Navbar from './components/Navbar';
import { Routes, Route } from 'react-router-dom';
import CountryDetails from './components/CountryDetails';
function App() {
const [countries, setCountries] = useState([]);
useEffect(() => {
fetch('https://ih-countries-api.herokuapp.com/countries')
.then((response) => response.json())
.then((data) => {
data.sort((a, b) => a.name.common.localeCompare(b.name.common));
setCountries(data);
});
}, []);
return (
<div className="App">
<Navbar />
<div className="container">
<div className="row">
<div className="col">
<CountriesList countries={countries} />
</div>
<div className="col">
<Routes>
<Route path="/:id" element={<CountryDetails />} />
{/* React-Router Route rendering the CountryDetails should go here */}
</Routes>
</div>
</div>
</div>
</div>
);
}
export default App;
import { Link } from 'react-router-dom';
const CountriesList = (props) => {
return (
<div>
<ul>
{props.countries.map((country) => (
<li key={country.alpha3Code}>
<Link to={`/${country.alpha3Code}`}>
<img
src={`https://flagpedia.net/data/flags/icon/72x54/${country.alpha2Code.toLowerCase()}.png`}
alt={country.name.common}
/>
<span>{country.name.common}</span>
</Link>
</li>
))}
</ul>
</div>
);
};
export default CountriesList;
import { useParams, Link } from 'react-router-dom';
import { useEffect, useState } from 'react';
const CountryDetails = () => {
const { id } = useParams();
const [country, setCountry] = useState(null);
useEffect(() => {
fetch(`https://ih-countries-api.herokuapp.com/countries/${id}`)
.then((response) => response.json())
.then((data) => {
setCountry(data);
});
}, [id]);
return (
<div>
{country && (
<>
<img
src={`https://flagpedia.net/data/flags/icon/72x54/${country.alpha2Code.toLowerCase()}.png`}
alt={country.name.common}
/>
<h1>{country.name.common}</h1>
<table class="table">
<tbody>
<tr>
<th scope="row">Capital</th>
<td>{country.capital.join(', ')}</td>
</tr>
<tr>
<th scope="row">Area</th>
<td>
{country.area} km<sup>2</sup>
</td>
</tr>
{country.borders.length > 0 && (
<tr>
<th scope="row">Borders</th>
<td>
<ul>
{country.borders.map((code) => (
<li key={code}>
<Link to={`/${code}`}>{code}</Link>
</li>
))}
</ul>
</td>
</tr>
)}
</tbody>
</table>
</>
)}
</div>
);
};
export default CountryDetails;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment