Created
November 24, 2022 19:03
-
-
Save josecarneiro/d1dd6e58c9cfd4b10eee255becb915c1 to your computer and use it in GitHub Desktop.
This file contains 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 { useState } from 'react'; | |
import contactList from './contacts.json'; | |
function App() { | |
const [contacts, setContacts] = useState(contactList.slice(0, 5)); | |
const handleAddRandomContact = () => { | |
const remainingContacts = contactList.filter((contact) => { | |
return !contacts.includes(contact); | |
}); | |
if (remainingContacts.length) { | |
const randomContact = | |
remainingContacts[Math.floor(Math.random() * remainingContacts.length)]; | |
setContacts([...contacts, randomContact]); | |
} | |
}; | |
const handleSortByName = () => { | |
const sortedContacts = [...contacts]; | |
sortedContacts.sort((a, b) => { | |
return a.name.localeCompare(b.name); | |
}); | |
setContacts(sortedContacts); | |
}; | |
const handleSortByPopularity = () => { | |
const sortedContacts = [...contacts]; | |
sortedContacts.sort((a, b) => { | |
return b.popularity - a.popularity; | |
}); | |
setContacts(sortedContacts); | |
}; | |
const handleDeleteContact = (id) => { | |
const contactsExcludingDeletedContact = contacts.filter((contact) => { | |
return contact.id !== id; | |
}); | |
setContacts(contactsExcludingDeletedContact); | |
}; | |
return ( | |
<div className="App"> | |
<button onClick={handleAddRandomContact}>Add Random Contact</button> | |
<button onClick={handleSortByName}>Sort by name</button> | |
<button onClick={handleSortByPopularity}>Sort by Popularity</button> | |
<table> | |
<thead> | |
<tr> | |
<th>Picture</th> | |
<th>Name</th> | |
<th>Popularity</th> | |
<th>Won Oscar</th> | |
<th>Won Emmy</th> | |
<th>Actions</th> | |
</tr> | |
</thead> | |
<tbody> | |
{contacts.map((contact) => { | |
return ( | |
<tr key={contact.id}> | |
<td> | |
<img src={contact.pictureUrl} /> | |
</td> | |
<td>{contact.name}</td> | |
<td>{contact.popularity.toFixed(2)}</td> | |
<td>{contact.wonOscar && '🏆'}</td> | |
<td>{contact.wonEmmy && '🏆'}</td> | |
<td> | |
<button onClick={() => handleDeleteContact(contact.id)}> | |
Delete | |
</button> | |
</td> | |
</tr> | |
); | |
})} | |
</tbody> | |
</table> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment