I have a list of products and I want to add a few more data like price and quantity. The problem is I lose input focus when I start typing because the entire list is being re-rendered. I have a simple Fiddle replicating that piece of code:
const App = () => {
// List of products
const [products, setProducts] = React.useState([
{
title: 'My Product',
},
{
title: 'My Product 2',
}
]);
// Simple debug to track changes
React.useEffect(() => {
console.log('PRODUCTS', products);
}, [products]);
const ProductForm = ({ data, index }) => {
const handleProductChange = (name, value) => {
const allProducts = [...products];
const selectedProduct = {...allProducts[index]};
allProducts[index] = {
...selectedProduct,
[name]: value
};
setProducts([ ...allProducts ]);
}
return (
<li>
<h2>{data.title}</h2>
<label>Price:</label>
<input type="text" value={products[index].price} onChange={(e) => handleProductChange('price', e.target.value)} />
</li>
);
}
return <ul>{products.map((item, index) => <ProductForm key={item.title} index={index} data={item} />)}</ul>;
}
ReactDOM.render(
<App />,
document.getElementById('container')
);
https://jsfiddle.net/lucasbittar/zh1d6y37/23/
I've tried a bunch of solution I found here but none of them really represents what I have.
Thanks!