aboutsummaryrefslogtreecommitdiff
path: root/part2/phonebook/src/App.js
blob: 2e430f97791a38c40cbaf8e9f8087c5763029831 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { useState } from 'react'

const ShowPerson = (props) => {
  const persons = props.persons
  return (
    <ol>
      {persons.map( (person) => {
        return (<li key={person.id}>{person.name}</li>)
      } )}
    </ol>
  )
}

const App = () => {
  const [persons, setPersons] = useState([
    { name: 'Arto Hellas' }
  ])
  const [newName, setNewName] = useState('')

  const addNumber = (event) => {
    event.preventDefault()
    console.log(newName, persons)
    const newPerson = {
      name: newName,
      id: persons.length + 1,
    }
    setPersons(persons.concat(newPerson))
  }

  const handleTypedName = (event) => {
    console.log(event.target.value)
    setNewName(event.target.value)
    console.log(newName)
  }

  return (
    <div>
      <h2>Phonebook</h2>
      <form onSubmit={addNumber}>
        <div>
          name: <input value={newName} onChange={handleTypedName} />
        </div>
        <div>
          <button  type="submit">add</button>
        </div>
      </form>
      <h2>Numbers</h2>
      <ShowPerson persons={persons}/>
    </div>
  )
}

export default App