I'm quite new to Hooks and I am trying to build a small address book.
So I have two components:
- A ContactCard component
- A ContactsList component
I want cards to be removed when the X is clicked. I managed to toggle the deleted prop of my contact, but I can't figure out how to force re-render the ContactsList
then
import React, { useState } from 'react'
import ContactsList from './components/contacts-list/contacts-list.component'
import './App.scss'
function App() {
const [contacts] = useState([
{
key: 0,
name: 'Lennon',
firstname: 'John',
notes: 'smart guy',
deleted: false
},
{
key: 1,
name: 'Starr',
firstname: 'Ringo',
notes: 'funny guy',
deleted: false
}
])
return (
<div className='App'>
<ContactsList contacts={contacts} />
</div>
)
}
export default App
import React, { useState, useEffect } from 'react'
import ContactCard from '../contact-card/contact-card.component'
import './contacts-list.styles.scss'
function ContactsList(props) {
const [contacts, setContacts] = useState(props.contacts)
return (
<div className='contacts-list'>
<span className='title'>Contacts</span>
{contacts
.filter(contact => contact.deleted === false)
.map(contact => (
<ContactCard
name={contact.name}
firstname={contact.firstname}
notes={contact.notes}
deleted={contact.deleted}
/>
))}
<hr />
</div>
)
}
export default ContactsList
import React, { useState } from 'react'
import './contact-card.styles.scss'
function ContactCard(props) {
const [contact, setContact] = useState([
{
name: props.name,
firstname: props.firstname,
notes: props.notes,
deleted: false
}
])
function deleteContact() {
const currentContact = [...contact]
currentContact[0].deleted = true
setContact(currentContact)
}
return (
<div className='contact-card'>
<span className='contact-name'>{props.name}</span>
<span className='delete-contact' onClick={deleteContact}>
✕
</span>
<br />
<span className='contact-firstname'>{props.firstname}</span>
<hr className='separator' />
<span className='contact-notes'>{props.notes}</span>
</div>
)
}
export default ContactCard