Skip to content

Instantly share code, notes, and snippets.

@catmando
Created March 16, 2019 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save catmando/9f70282e000783fbfb10c60083a105a5 to your computer and use it in GitHub Desktop.
Save catmando/9f70282e000783fbfb10c60083a105a5 to your computer and use it in GitHub Desktop.
import React, {Component} from 'react';
import './ToDo.css';
import ToDoItem from './components/ToDoItem';
import Logo from './assets/logo.png';
class ToDo extends Component {
constructor(props) {
super(props);
this.state = {
// this is where the data goes
list: [
{
'todo': 'clean the house'
},
{
'todo': 'buy milk'
}
],
todo: ''
};
};
createNewToDoItem = () => {
this.setState(({ list, todo }) => ({
list: [
...list,
{
todo
}
],
todo: ''
}));
};
handleKeyPress = e => {
if (e.target.value !== '') {
if (e.key === 'Enter') {
this.createNewToDoItem();
}
}
};
handleInput = e => {
this.setState({
todo: e.target.value
});
};
// this is now being emitted back to the parent from the child component
deleteItem = indexToDelete => {
this.setState(({ list }) => ({
list: list.filter((toDo, index) => index !== indexToDelete)
}));
};
render() {
return (
<div className="ToDo">
<img className="Logo" src={Logo} alt="React logo"/>
<h1 className="ToDo-Header">React To Do</h1>
<div className="ToDo-Container">
<div className="ToDo-Content">
{this.state.list.map((item, key) => {
return <ToDoItem
key={key}
item={item.todo}
deleteItem={this.deleteItem.bind(this, key)}
/>
}
)}
</div>
<div>
<input type="text" value={this.state.todo} onChange={this.handleInput} onKeyPress={this.handleKeyPress}/>
<button className="ToDo-Add" onClick={this.createNewToDoItem}>+</button>
</div>
</div>
</div>
);
}
}
export default ToDo;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment