Created
February 12, 2018 13:59
-
-
Save codewithbernard/3abf8e6eb9ad9d3cf4a87bd217b3f3cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import _ from 'lodash'; | |
class MealPlan extends Component { | |
state = { | |
meal: '', | |
meals: [], | |
showAddMealMessage: false | |
}; | |
renderMeals() { | |
return _.map(this.state.meals, meal => <li>{meal}</li>); | |
} | |
componentWillMount() { | |
this.setState({meals: ["Eggs with bacon", "Spaghetti carbonara", "Oatmeal"]}); | |
} | |
componentDidUpdate(prevProps, prevState) { | |
if (prevState.meals.length < this.state.meals.length) { | |
this.setState({showAddMealMessage: true}); | |
setTimeout(() => this.setState({showAddMealMessage: false}), 1000); | |
} | |
} | |
handleSubmit = (event) => { | |
event.preventDefault() | |
const meal = this.state.meal; | |
this.setState({ | |
meals: [...this.state.meals, meal], | |
meal: "" | |
}); | |
} | |
render() { | |
return( | |
<div> | |
<h2>Today you should eat this</h2> | |
<form onSubmit={e => this.handleSubmit(e)}> | |
<input | |
onChange={e => this.setState({meal: e.target.value})} | |
value={this.state.meal} | |
type="text" | |
/> | |
<button | |
type="submit">Add meal</button> | |
</form> | |
{this.state.showAddMealMessage ? <p>New meal added</p> : null} | |
<ul> | |
{this.renderMeals()} | |
</ul> | |
</div> | |
); | |
} | |
} | |
export default MealPlan; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment