React Base Fiddle (JSX)
Starting point for creating JSFiddles with React.
HTML
<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>
React
var arr = [{
"catName": "Category 1",
"fields": [
{
"name": "field 1",
"amount": "0"
},
{
"name": "field 2",
"amount": "0"
}
]
},
{
"catName": "Category 2",
"fields": [
{
"name": "field 1",
"amount": "0"
},
{
"name": "field 2",
"amount": "0"
}]
}]
class Main extends React.Component {
state = {
list: arr
};
handleChange = (e, fieldName, catName) => {
//get list from state
const { list } = this.state
//this returns the related item's index, I assume that all cats have a unique name, otherwise you should use unique values such as IDs
const targetCatIndex = list.findIndex(item => item.catName === catName)
//find related field index
const targetFieldIndex = list[targetCatIndex].fields.findIndex(item => item.name === fieldName)
//update the field and assign to state
list[targetCatIndex].fields[targetFieldIndex].amount = e.target.value
this.setState({ list: list });
}
render() {
return (<div>
{this.state.list.map(item => (
<Category
id={item.catName}
name={item.catName}
key={item.catName}
list={item}
handleChange={this.handleChange}
/>
))}
</div>);
}
}
const Category = ({ name, list, handleChange }) => {
return (
<div className="section">
<h3>{name}</h3>
{list.fields.map(item => (
<Item
id={item.name}
name={item.name}
key={item.name}
list={item}
// pass field and cat referance with input event
handleChange={(e, fieldName) => handleChange(e,...