import {useState, useEffect } from 'react'
import axios from 'axios'
const Countries = ({searchedCountries}) => {
console.log(searchedCountries.map(c => c.languages))
if (searchedCountries.length >= 10) {
return (
<div>
<p>too many countries to list, please narrow your search</p>
</div>
)
}
if (searchedCountries.length === 1) {
return (
<div>
capital: {searchedCountries.map(c => <p>{c.capital}</p>)}
area: {searchedCountries.map(c => <p>{c.area}</p>)}
<h2>Languages</h2>
<ul>
{searchedCountries.map(c => <li>{Object.values(c.languages)}</li>)}
</ul>
{searchedCountries.map(c => <img src={Object.values(c.flags)[0]} /> )}
</div>
)
}
return (
<ul>
{searchedCountries.map(c => <li>{c.name.common}</li>)}
</ul>
)
}
const App = () => {
const [countries, setCountries] = useState([])
const [newSearch, setNewSearch] = useState('')
const handleSearchChange = (event) => {
setNewSearch(event.target.value)
}
const searchedCountries =
countries.filter(c => c.name.common.includes(newSearch))
useEffect(() => {
console.log('effect')
axios
.get('https://restcountries.com/v3.1/all')
.then(response => {
console.log('promise fulfilled')
setCountries(response.data)
})
}, [])
return (
<div>
<div><p>find countries</p><input value={newSearch} onChange={handleSearchChange} /></div>
<div>
<h2>countries</h2>
<Countries searchedCountries={searchedCountries} />
</div>
</div>
)
}
export default App;
I am trying to list the languages of each country in my app, however, the languages render like this:
-EnglishSwedishItalian
instead of like this:
- English
- Swedish
- Italian
Does anyone know how to render each of the Object.values(c.lanaguages) on its own line instead of all bunched together on one line?
Thanks.
CodePudding user response:
You're passing an array (Obect.values(c.languages)
) in a single <li>
which gets flattened to a string by React.
<ul>
{searchedCountries.map(c => <li>{Object.values(c.languages)}</li>)}
</ul>
You'll need to instead map()
the values array.
<ul>
{
searchedCountries.map(c =>
<li>
<ul>
{Object.values(c.languages).map(l => <li>{l}</li>)}
</ul>
</li>
)
}
</ul>