-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathform.js
82 lines (75 loc) · 2.25 KB
/
form.js
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
import './App.css';
import { useState } from 'react';
// Build a simple React.js form | React Form Validation
const MyForm = () => {
const [form, setForm] = useState({});
const updateForm = (e, fieldName) => {
setForm({
...form,
[fieldName]: fieldName === 'age' ? Number(e.target.value) : e.target.value
});
e.target.setCustomValidity('');
}
const onSubmit = (e) => {
e.preventDefault();
console.log(form);
// rest of actions
}
return (
<div className="container">
<div className="myFormText">My form</div>
<form onSubmit={(e) => onSubmit(e)}>
<label htmlFor="name">
<input
type="text"
className="myInput"
name="name"
onInvalid={ (e) => {
e.target.setCustomValidity('Please insert your name.');
}}
id="name"
value={ form.name || '' }
onChange={ (e) => updateForm(e, 'name') }
required={ true }
placeholder="Add your name"
/>
</label>
<label htmlFor="age">
<input
type="number"
className="myInput"
onInvalid={ (e) => {
e.target.setCustomValidity('Please insert your age.');
}}
value={ form.age || '' }
onChange={ (e) => updateForm(e, 'age') }
name="age"
id="age"
required={ true }
placeholder="Add your age"
/>
</label>
<label htmlFor="description">
<textarea
type="text"
value={ form.description || '' }
className="myInput"
onInvalid={ (e) => {
e.target.setCustomValidity('Please insert your description.');
}}
name="description"
onChange={ (e) => updateForm(e, 'description') }
id="description"
rows={ 10 }
required={ true }
placeholder="Add your description"
/>
</label>
<button type="submit" className="myButton">
Submit
</button>
</form>
</div>
);
}
export default MyForm;