I am trying to learn React JS and I am working on a personal project. I am stuck because I could not pass the value of an input field in a child component to the state of the parent component.
I have tried using the onChange event but for some reason the function it is calling, handleChange, is not getting triggered.
Here is a snippet from the Parent component:
class App extends Component {
state = {
myArray: [{ //myArray is being updated by another child component, which sets the values for id and amount; this works fine
id: 1,
amount: 12
},
{
id: 2,
amount: 23
}
]
total: 0 //expected value for total is 35
};
handleChange = e => {
const { name, value } = e.target
this.setState({
[name]: value
});
}
render() {
return (
<Child
handleChange={this.handleChange}
myArray={this.state.myArray} />
)
}
}
And here is a snippet from the Child component:
class Child extends Component {
render() {
const { myArray, handleChange } = this.props;
const totalAmount = myArray.reduce(function (a, b) {
return a + b.amount;
}, 0);
return (
<div>
<label htmlFor="total"> Total Amount: </label>
<input id="total"
name="total"
type="number"
placeholder="0.00"
value={totalAmount}
onChange={e => handleChange(e)}
/>
</div>
)
}
}
The value in of the total input field renders correctly. However, what I am trying to achieve is every time this input field value is changed (when the other child component updates the myArray values and therefore the sum also changes), I wish to update the total value in the state of the Parent component.