From b781e622fa3e300a721339df422634a826085e7a Mon Sep 17 00:00:00 2001 From: Ibrahim Mkusa Date: Sun, 30 Apr 2023 15:02:18 -0400 Subject: ex2.9 dynamically search for phone numbers on the fly --- part2/phonebook/src/App.js | 38 ++++++++++++++++++++++++++------------ 1 file 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 ( -
    - {persons.map( (person) => { - return (
  1. {person.name} {person.phoneNumber}
  2. ) - } )} -
- ) -} 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 (
  • {person.name} {person.phoneNumber}
  • )}) + } else { + const searchedList = persons.filter( (person) => + {return person.name.includes(searchTerm)}); + console.log(searchedList) + return searchedList.map( (searched) => { + return (
  • {searched.name} {searched.phoneNumber}
  • ) + } ) + } + } + + return (

    Phonebook

    +

    filter shown with

    +

    add new contact

    name:

    @@ -55,7 +69,7 @@ const App = () => {

    Numbers

    - +
    ) } -- cgit v1.2.3