I have a React form with dynamic input fields that a user can add and remove input fields. When i submit the form, i log the values from each input in an array. The problem is that i can’t type continuously in a input. When i type in input, i can type only one character and it focus out. How can i fix it?
App.js
JavaScript
x
64
64
1
import React, { useState } from "react";
2
import ReactDOM from "react-dom";
3
4
import "./styles.css";
5
6
function App() {
7
const [fields, setFields] = useState([""]);
8
9
function handleChange(i, event) {
10
const values = [fields];
11
values[i] = event.target.value;
12
setFields(values);
13
}
14
15
function handleAdd() {
16
const values = [fields];
17
values.push("");
18
setFields(values);
19
}
20
21
function handleRemove(i) {
22
const values = [fields];
23
values.splice(i, 1);
24
setFields(values);
25
}
26
27
function submitHandler(event) {
28
event.preventDefault();
29
console.log(fields);
30
}
31
32
return (
33
<div className="App">
34
<h1>Hello CodeSandbox</h1>
35
<form onSubmit={submitHandler}>
36
<button type="button" onClick={() => handleAdd()}>
37
Add Input
38
</button>
39
40
{fields.map((field, idx) => {
41
return (
42
<div key={`${field}-${idx}`}>
43
<input
44
type="text"
45
placeholder="Enter text"
46
value={field || ""}
47
onChange={(e) => handleChange(idx, e)}
48
/>
49
<button type="button" onClick={() => handleRemove(idx)}>
50
X
51
</button>
52
</div>
53
);
54
})}
55
<button className="margin-top" type="submit">
56
Submit
57
</button>
58
</form>
59
</div>
60
);
61
}
62
63
export default App;
64
Advertisement
Answer
Replace your code with this
JavaScript
1
12
12
1
<div key={`${"asdf"}-${idx}`}>
2
<input
3
type="text"
4
placeholder="Enter text"
5
value={field || ""}
6
onChange={(e) => handleChange(idx, e)}
7
/>
8
<button type="button" onClick={() => handleRemove(idx)}>
9
X
10
</button>
11
</div>
12