Last active
May 22, 2017 13:27
-
-
Save celsowhite/2f276f71a857df8dbc41e56dabf18242 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 from 'react'; | |
import ReactDOM from 'react-dom'; | |
class ItemField extends React.Component { | |
render() { | |
return ( | |
<form onSubmit={(e) => this.props.onSubmit(e)}> | |
<input type="text" value={this.props.inputValue} onChange={(e) => this.props.onChange(e)} /> | |
<input type="submit" value="Submit" /> | |
</form> | |
) | |
} | |
} | |
class ListItem extends React.Component { | |
render() { | |
return ( | |
<li>{this.props.name} <span onClick={() => this.props.onClick(this.props.index)}>x</span></li> | |
) | |
} | |
} | |
class List extends React.Component { | |
constructor() { | |
super(); | |
this.state = { | |
groceryList: [], | |
groceryListHistory: [], | |
inputValue: '' | |
} | |
} | |
handleDelete(index) { | |
const groceryList = this.state.groceryList.slice(); | |
groceryList.splice(index, 1); | |
const groceryListHistory = this.state.groceryListHistory.slice(); | |
groceryListHistory.push(groceryList); | |
this.setState({ | |
groceryList: groceryList, | |
groceryListHistory: groceryListHistory | |
}) | |
} | |
handleChange(e) { | |
this.setState({ | |
inputValue: e.target.value | |
}) | |
} | |
handleSubmit(e) { | |
e.preventDefault(); | |
const groceryList = this.state.groceryList.slice(); | |
groceryList.push(this.state.inputValue); | |
const groceryListHistory = this.state.groceryListHistory.slice(); | |
groceryListHistory.push(groceryList); | |
this.setState({ | |
groceryList: groceryList, | |
groceryListHistory: groceryListHistory, | |
inputValue: '' | |
}); | |
} | |
render() { | |
const that = this; | |
return ( | |
<ul> | |
{this.state.groceryList.map(function(listValue, index){ | |
return <ListItem name={listValue} key={listValue.id} index={index} onClick={(index) => that.handleDelete(index)} />; | |
})} | |
<ItemField inputValue={this.state.inputValue} onSubmit={(e) => this.handleSubmit(e)} onChange={(e) => this.handleChange(e)} /> | |
</ul> | |
) | |
} | |
} | |
ReactDOM.render( | |
<List />, | |
document.getElementById('root') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment