<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Babel + JSX
const ProductForm = ({ data, index, handleProductChange }) => {
return (
<li>
<h2>{data.title}</h2>
<label>Price:</label>
<input
name="price" // <-- name input field
type="text"
value={data.price || ''} // <-- use data.price or fallback value
onChange={(e) => handleProductChange(e, index)} // <-- pass event and index
/>
</li>
);
}
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]);
// Update signature to also take index
const handleProductChange = (e, index) => {
const { name, value } = e.target; // <-- destructure name and value
const allProducts = [...products];
const selectedProduct = {...allProducts[index]};
allProducts[index] = {
...selectedProduct,
[name]: value
};
setProducts([ ...allProducts ]);
}
return (
<ul>
{products.map((item, index) => (
<ProductForm
key={item.title}
index={index}
data={item}
handleProductChange={handleProductChange} // <-- pass callback handler
/>)
)}
</ul>
);
}
ReactDOM.render(
<App />,
document.getElementById('container')
);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.