React input loses focus on each change. I know that if I move my Input function inside map directly it gonna work correctly. But I want to make it a reusable component. Here is the link: https://codesandbox.io/s/weathered-violet-j6gv14?file=/src/inputs.js
import React, { useState } from "react";
export default function Inputs({ inputs, setInputs }) {
function handleAdd() {
setInputs([...inputs, { input1: "", input2: "" }]);
}
function handleChange({ value, index, name }) {
const tempInputs = [...inputs];
tempInputs[index][name] = value;
setInputs(tempInputs);
}
function Input({ index, input, ...props }) {
return (
<div {...props}>
<input
type="text"
value={input["input1"]}
onChange={(e) =>
handleChange({
value: e.target.value,
index: index,
name: "input1",
})
}
/>
<input
value={input["input2"]}
onChange={(e) =>
handleChange({
value: e.target.value,
index: index,
name: "input2",
})
}
/>
</div>
);
}
return (
<div>
<button onClick={handleAdd}>Add</button>
<ul>
{inputs.map((input, index) => {
return <Input key={index} index={index} input={input} />;
})}
</ul>
</div>
);
}