diff options
author | Ibrahim Mkusa <ibrahimmkusa@gmail.com> | 2023-04-30 15:02:18 -0400 |
---|---|---|
committer | Ibrahim Mkusa <ibrahimmkusa@gmail.com> | 2023-04-30 15:02:18 -0400 |
commit | b781e622fa3e300a721339df422634a826085e7a (patch) | |
tree | 775e72e96586c17b4e75872134e5500490d42215 /part2 | |
parent | 7820cb0777d9d4c0479a926a06811c945f35654f (diff) |
ex2.9 dynamically search for phone numbers on the fly
Diffstat (limited to 'part2')
-rw-r--r-- | part2/phonebook/src/App.js | 38 |
1 files changed, 26 insertions, 12 deletions
diff --git a/part2/phonebook/src/App.js b/part2/phonebook/src/App.js index 15f9636..593018a 100644 --- a/part2/phonebook/src/App.js +++ b/part2/phonebook/src/App.js @@ -1,22 +1,15 @@ import { useState } from 'react' -const ShowPerson = (props) => { - const persons = props.persons - return ( - <ol> - {persons.map( (person) => { - return (<li key={person.id}>{person.name} {person.phoneNumber}</li>) - } )} - </ol> - ) -} const App = () => { const [persons, setPersons] = useState([ - { name: 'Arto Hellas', phoneNumber: '000-000-0000' } + { name: 'Arto Hellas', phoneNumber: '000-000-0000', id: 1 }, + { name: 'John F Kennedy', phoneNumber: '1-800-NASA', id: 2 }, + { name: 'Julius K Nyerere', phoneNumber: '1-800-UHURU', id: 3 }, ]) const [newName, setNewName] = useState('') const [phoneNumber, setPhoneNumber] = useState('') + const [searchTerm, setSearchTerm] = useState('') const addContact = (event) => { event.preventDefault() @@ -42,9 +35,30 @@ const App = () => { setPhoneNumber(event.target.value) } + const handleSearch = (event) => { + setSearchTerm(event.target.value) + } + + const ShowPerson = () => { + if (searchTerm === undefined) { + return persons.map( (person) => { + return (<li key={person.id}>{person.name} {person.phoneNumber}</li>)}) + } else { + const searchedList = persons.filter( (person) => + {return person.name.includes(searchTerm)}); + console.log(searchedList) + return searchedList.map( (searched) => { + return (<li key={searched.id}>{searched.name} {searched.phoneNumber}</li>) + } ) + } + } + + return ( <div> <h2>Phonebook</h2> + <p>filter shown with <input value={searchTerm} onChange={handleSearch} /></p> + <h2> add new contact </h2> <form onSubmit={addContact}> <div> <p>name: <input value={newName} onChange={handleTypedName} /></p> @@ -55,7 +69,7 @@ const App = () => { </div> </form> <h2>Numbers</h2> - <ShowPerson persons={persons}/> + <ShowPerson/> </div> ) } |