I'm new to React, so please explain why this is happens(I guess because I'm re-creating the array of objects, but I'm not sure and don't know how to fix this) and how to fix this this.
I think it's better to show the code, rather than talk about it, so:
App.js
import { useState } from "react";
import Input from "./Input";
let lastId = 2;
function App() {
const [inputsValues, setInputsValues] = useState([
{ id: 1, value: "" },
{ id: 2, value: "" },
]);
const handleChange = (e, id) => {
setInputsValues((prevState) => {
const newState = [...prevState];
const index = newState.findIndex((input) => input.id === id);
newState[index].value = e.target.value;
return newState;
});
};
const addNewInput = () => {
setInputsValues((prevState) => {
const newState = [...prevState];
newState.push({ id: ++lastId, value: "" });
return newState;
});
};
return (
<div className="App">
<div>
<button onClick={addNewInput}>Add new input...</button>
</div>
{inputsValues.map((input) => (
<div className="input-wrap">
<Input
key={input.id}
id={input.id}
value={input.value}
handleChange={handleChange}
/>
</div>
))}
</div>
);
}
export default App;
Input.js
import { useRef } from "react";
const Input = ({ id, value, handleChange }) => {
const renderAmount = useRef(0);
return (
<>
<div> Rendered: {renderAmount.current++}</div>
<input
id={id}
type="text"
value={value}
onChange={(e) => handleChange(e, id)}
/>
</>
);
};
export default Input;
Thanks