Skip to content

Instantly share code, notes, and snippets.

@codingnninja
Created August 6, 2019 05:20
Show Gist options
  • Save codingnninja/891aa0444351a188ad97d2a8f3abb469 to your computer and use it in GitHub Desktop.
Save codingnninja/891aa0444351a188ad97d2a8f3abb469 to your computer and use it in GitHub Desktop.
Adding items to state.
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
id: null,
userId: 1,
food: '',
cost: '',
status: false,
foodItem: {},
foodItems: [],
editing: false
};
this.handleInputChange = this.handleInputChange.bind(this);
this.addFoodItem = this.addFoodItem.bind(this);
}
handleInputChange(event) {
event.preventDefault();
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]:value
})
}
addFoodItem(event){
event.preventDefault()
if (!this.state.food) return;
const foodItem = {
id: this.state.foodItems.length + 1,
food: this.state.food,
cost: this.state.cost,
userId: this.state.userId,
statu: this.state.status
};
this.setState({
food: '',
cost: '',
foodItem: foodItem,
foodItems: [...this.state.foodItems, foodItem]
})
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment