-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathFormExample.js
More file actions
executable file
·100 lines (81 loc) · 2.07 KB
/
Copy pathFormExample.js
File metadata and controls
executable file
·100 lines (81 loc) · 2.07 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Good article to read on form https://medium.com/javascript-inside/better-understanding-forms-in-react-a85d889773ce
import React from 'react'
function ControlledInputBox (props) {
const { handleInputChange, textBoxValue } = props
return <input type='text' value={textBoxValue} onChange={handleInputChange} />
}
function ButtonComponent (props) {
return <button>Save changes</button>
}
class MyComponent extends React.Component {
state = {
cityArray: ['Karachi', 'Lahore', 'Peshawar', 'Quetta'],
textBoxValue: ''
}
handleInputChange = e => {
const { value } = e.target
this.setState({
textBoxValue: value
})
}
addCity = () => {
const { textBoxValue } = this.state
this.setState(prevState => ({
cityArray: [...prevState.cityArray, textBoxValue],
textBoxValue: ''
}))
}
removeCity = event => {
const { cityArray } = this.state
const { value } = event.target
const newCityArray = cityArray.filter(city => city !== value)
this.setState({
cityArray: newCityArray
})
}
handleForm = event => {
const { textBoxValue } = this.state
event.preventDefault()
if (textBoxValue === '') {
alert('Please enter city name to save')
} else {
this.addCity()
}
}
render () {
const { cityArray, textBoxValue } = this.state
return (
<form onSubmit={this.handleForm}>
<ul>
{cityArray.map(city => (
<li key={city}>
{' '}
{city}{' '}
<button value={city} onClick={this.removeCity}>
X
</button>
</li>
))}
</ul>
<ControlledInputBox
textBoxValue={textBoxValue}
handleInputChange={this.handleInputChange}
/>
<ButtonComponent />
</form>
)
}
}
function MyFunctionalComponent (props) {
const { heading } = props
return <h1>{heading}</h1>
}
function App () {
return (
<div>
<MyFunctionalComponent heading='Cities List' />
<MyComponent />
</div>
)
}
export default App