-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex1_useRef.html
115 lines (92 loc) · 2.88 KB
/
ex1_useRef.html
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<!-- compilation JSX => JS -->
<script type="text/babel">
const InputText = () => {
const inputRef = React.useRef(null);
return (
<div>
<input ref={inputRef} type="text" />
</div>
);
}
function Form(props) {
let [error, setError] = React.useState(false);
let [moyenne, setMoyenne] = React.useState(0)
let inputRef = []
for (let i = 0; i<5; i++) {
inputRef.push(React.useRef(null))
}
const handleSubmit = (e) => {
e.preventDefault()
let somme = 0;
inputRef.forEach((e,i) => {
somme = somme + Number(e.current.value)
console.log('elemenent'+(i+1)+' : '+ e.current.value)
if(e.current.value == '') {
setError(true)
}
});
if(error) setMoyenne(somme/inputRef.length);
console.log(moyenne)
}
return(<form>
{
props.notes.map((el,key)=> {
return(<div key={key}>
<div className="form-group">
<label htmlFor={'field_note'+key+1}>{el.title}: </label>
<input name={'field_note'+key+1} ref={inputRef[key]} type="number" />
</div>
</div>)
})
}
<button type="submit" onClick={handleSubmit}>Calculer Moyenne</button>
{(error && moyenne ==0) && <div style={{color: 'red'}}>{'Merci de remplir tout les champs'}</div>}
{moyenne !=0 && <p>Moyenne : {moyenne}</p>}
</form>)
}
function App(){
const notes = [
{
title: 'matiere 1',
coefficient: '1'
},
{
title: 'matiere 2',
coefficient: '1'
},
{
title: 'matiere 3',
coefficient: '1'
},
{
title: 'matiere 4',
coefficient: '1'
},
{
title: 'matiere 5',
coefficient: '1'
}
]
return(
<div>
<Form notes={notes} />
</div>)
}
ReactDOM.render(
<App/>,
document.getElementById('root')
);
</script>
</body>
</html>