I'm having a problem on inputs than want to change in array, there is a lot of lag/delay when typing in inputs when this array have more than 8 arraylists, i make this code below to simple reproduce what's happen with my code.
App.js
import './App.css';
import React,{useState} from 'react';
import Inputs from './Inputs'
function App() {
const [ array, setArray ] = useState([
["John",'30','ttt'],
["Smith",'20','ttt'],
["Thiago",'40','ttt'],
["Jake",'30','ttt'],
["Fer",'41','ttt'],
["Fred",'23','ttt'],
["Otto",'55','ttt'],
["Gago",'21','ttt'],
["Higor",'15','ttt'],
]);
return (
<div className="App">
<header className="App-header">
<Inputs array={array} setArray={setArray} />
<br />
<button onClick={() => {
/** add More arrays */
setArray(array=> [...array, ['','','']])
}}>add more</button>
<br />
<button onClick={() => console.log("Send array to DB")}>Send array to DB</button>
</header>
</div>
);
}
export default App;
Inputs.js
import './App.css';
import React,{ useEffect } from 'react';
function Inputs(props) {
const { array, setArray } = props
const handleInputChange = (e, index, position2) => {
const {value} = e.target;
const list = [...array];
list[index][position2] = value;
setArray(list);
};
useEffect(() => {
console.log(array)
},[array])
return (
array.map((item, index) => {
return (<div key={index}>
<input
value={item[0]}
onChange={(e) => {
handleInputChange(e,index,0)
}}
/>
<input
value={item[1]}
onChange={(e) => {
handleInputChange(e,index,1)
}}
/>
<input
value={item[2]}
onChange={(e) => {
handleInputChange(e,index,2)
}}
/>
</div>)
})
);
}
export default Inputs;
I don't find another option to change value in this array, and each type in inputs are creating every arrays again.
Thanks
You can consider maintaining separate states for all the inputs instead of creating a common state.
A better alternative to this will be to create a pure component that can be used for rendering all the inputs - Then you will just have to pass the value and onChange callback.