Skip to content

Instantly share code, notes, and snippets.

@schinns
Created November 5, 2020 04:22
Show Gist options
  • Save schinns/6a478015a511163c95473ab35b564ba6 to your computer and use it in GitHub Desktop.
Save schinns/6a478015a511163c95473ab35b564ba6 to your computer and use it in GitHub Desktop.
iterate over a list of data received from a server, creating a set of components and adding them to the DOM
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Components II</title>
</head>
<body>
<h1>Pokedex</h1>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
axios.get('https://pokeapi.co/api/v2/pokemon?offset=100&limit=100')
.then(res => {
console.log(res.data.results)
res.data.results.forEach(pokemon => {
//add a pokemon card component
axios.get(pokemon.url)
.then(res => {
const newCard = pokemonCard(pokemon.name, res.data.sprites.front_default)
document.querySelector('body').appendChild(newCard)
})
.catch(err => console.log(err))
})
})
.catch(err => console.log(err))
function pokemonCard(name, imgUrl) {
const cardContainer = document.createElement('div')
const cardTitle = document.createElement('h3')
const img = document.createElement('img')
img.src = imgUrl
const s = cardContainer.style
s.backgroundColor = 'pink'
s.width = '300px'
s.height = '300px'
s.display = 'flex'
s.alignItems = 'center'
s.justifyContent = 'center'
s.flexDirection = 'column'
s.marginBottom = '5px'
cardTitle.textContent = name
cardContainer.appendChild(cardTitle)
cardContainer.appendChild(img)
return cardContainer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment