The problem is that you are missing the part of indicating which object to update,
you can do so by passing the index of the array or by the id that the object has.
for example:
function handleChange(e){
const value = e.target.value;
const tempWorkingHours = data.working_hours.map((item) => {
if (item.id === value.id) {
return {
...item,
price: value
}
}
return item;
}
setData({...data, working_hours: tempWorkingHours })
}
in that way, you are using a map to loop over the array and find the item you want to change(but by the temp variable that holds a copy of the data to avoid mutating the state).
You can also pass the index to the handle change function:
{data.working_hours.map((item, index) =>
<>
<input type={text} value={item.description}
onChange={(e) => handleChange(e)} />
<input type={text} value={item.price}
onChange={(e,index) => handleChange(e, index)} />
</>
)}
And then in the handleChange use the index to access the relevant index to change the array. let me know if you want me to explain more with modification of your code, but I think the way I explain above with the id solution is nice.
Edit- the index version :
function handleChange(e, index) {
const value = e.target.value;
const tempWorkingHours = [...data.working_hours];
tempWorkingHours[index].price = value;
setData({...data, working_hours: tempWorkingHours});
}
Fixed the first example, the return moved outside the if statement in case it's not the relevant id we want to modify.
Read more about forms from react's official docs:
https://reactjs.org/docs/forms.html
It doesn't matter if you are using function components to get the point, its the same. Only the way You are updating the state is with
useState.
class Reservation extends React.Component {
constructor(props) {
super(props);
this.state = {
isGoing: true,
numberOfGuests: 2
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<form>
<label>
Is going:
<input
name="isGoing"
type="checkbox"
checked={this.state.isGoing}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Number of guests:
<input
name="numberOfGuests"
type="number"
value={this.state.numberOfGuests}
onChange={this.handleInputChange} />
</label>
</form>
);
}
}