Skip to content

Instantly share code, notes, and snippets.

@josecarneiro
Created March 23, 2021 20:40
Show Gist options
  • Save josecarneiro/672c518f6abef3cbf5e364dc96dcb9c4 to your computer and use it in GitHub Desktop.
Save josecarneiro/672c518f6abef3cbf5e364dc96dcb9c4 to your computer and use it in GitHub Desktop.
import './App.css';
import { BrowserRouter, Route } from 'react-router-dom';
import CountryDetails from './components/CountryDetails';
import Navbar from './components/Navbar';
import CountryList from './components/CountryList';
import countries from './countries.json';
function App() {
return (
<BrowserRouter>
<div className="wrapper">
<Navbar />
<aside>
<CountryList countries={countries} />
</aside>
<main>
<Route path="/:countryCode" component={CountryDetails} />
</main>
</div>
</BrowserRouter>
);
}
export default App;
import React, { Component } from 'react';
import countries from './../countries.json';
import { Link } from 'react-router-dom';
class CountryDetails extends Component {
state = {
country: null,
};
componentDidMount() {
this.loadCountry();
}
componentDidUpdate(previousProps) {
if (
this.props.match.params.countryCode !==
previousProps.match.params.countryCode
) {
this.loadCountry();
}
}
loadCountry() {
const countryCode = this.props.match.params.countryCode;
const country = countries.find((item) => item.cca3 === countryCode);
this.setState({
country: country,
});
}
getCountryName(countryCode) {
return countries.find((item) => item.cca3 === countryCode).name.common;
}
render() {
const country = this.state.country;
return (
<div>
<h1>{this.props.match.params.countryCode}</h1>
{country && (
<div>
<h1>{country.name.common}</h1>
<table>
<thead></thead>
<tbody>
<tr>
<td style={{ width: '30%' }}>Capital</td>
<td>{country.capital[0]}</td>
</tr>
<tr>
<td>Area</td>
<td>
{country.area} km
<sup>2</sup>
</td>
</tr>
<tr>
<td>Borders</td>
<td>
<ul>
{country.borders.map((countryCode) => (
<li key={countryCode}>
<Link href={`/${countryCode}`}>
{this.getCountryName(countryCode)}
</Link>
</li>
))}
</ul>
</td>
</tr>
</tbody>
</table>
</div>
)}
</div>
);
}
}
export default CountryDetails;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment