Created
July 8, 2021 01:11
-
-
Save NickFoden/c4e6011b9f14fa95209cea35c6914e46 to your computer and use it in GitHub Desktop.
Flag Filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from "react"; | |
import axios from "axios"; | |
import Flags from "../components/Flags"; | |
import styled from "styled-components"; | |
import Pagination from "../components/Pagination"; | |
const Homepage = () => { | |
const [flags, setFlags] = useState([]); | |
const [loading, setLoading] = useState(false); | |
const [currentPage, setCurrentPage] = useState(1); | |
const [flagsPerPage, setFlagsPerPage] = useState(8); | |
const [query, setQuery] = useState(""); | |
let tempFlags = flags; | |
if (query) { | |
tempFlags = tempFlags.filter((F) => F.name.toLowerCase().includes(query.toLowerCase())); | |
// Fuzzy Search | |
} | |
const indexOfLastFlag = currentPage * flagsPerPage; | |
const indexOfFirstFlag = indexOfLastFlag - flagsPerPage; | |
const currentFlags = tempFlags.slice(indexOfFirstFlag, indexOfLastFlag); | |
// switch to the page | |
const paginate = (pageNumber) => setCurrentPage(pageNumber); | |
useEffect(() => { | |
const fetchFlags = async () => { | |
setLoading(true); | |
if (query) { | |
let { data } = await axios.get( | |
`https://restcountries.eu/rest/v2/name/${query}` | |
); | |
setFlags(data); | |
setLoading(false); | |
} else { | |
let { data } = await axios.get("https://restcountries.eu/rest/v2/"); | |
setFlags(data); | |
setLoading(false); | |
} | |
}; | |
fetchFlags(); | |
}, []); | |
return ( | |
<StyledHomeWrapper> | |
<StyledSearchWrapper> | |
<StyledSearch> | |
<input | |
type="text" | |
value={query} | |
onChange={(e) => setQuery(e.target.value)} | |
placeholder="Search for country" | |
/> | |
</StyledSearch> | |
</StyledSearchWrapper> | |
<Flags flags={currentFlags} /> | |
<Pagination | |
flagsPerPage={flagsPerPage} | |
totalFlags={flags.length} | |
paginate={paginate} | |
/> | |
</StyledHomeWrapper> | |
); | |
}; | |
export default Homepage; | |
const StyledHomeWrapper = styled.div` | |
background-color: #fafafa; | |
flex: 1 1 auto; | |
height: 100%; | |
display: flex; | |
flex-direction: column; | |
color: black; | |
`; | |
const StyledSearch = styled.div` | |
div { | |
width: 100%; | |
display: block; | |
} | |
input { | |
padding: 3rem; | |
border: 1px solid #ececec; | |
width: 100%; | |
display: block; | |
border-radius: 0.5rem; | |
font-size: 1.7rem; | |
} | |
`; | |
const StyledSearchWrapper = styled.div` | |
display: flex; | |
justify-content: space-between; | |
margin: 0 auto; | |
max-width: 130rem; | |
width: 100%; | |
margin-top: 3rem; | |
`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment