Created
March 10, 2020 18:17
-
-
Save aaronmaldonado-dev/8e638db938fa45dcde5d28cf5605165c to your computer and use it in GitHub Desktop.
React - basic todo list component
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, { useState } from 'react'; | |
import Uniqid from 'uniqid'; | |
function ListItems(props) { | |
return( | |
props.items.map( | |
(item, index) => | |
<li key={index}> | |
<input type="checkbox" checked={item.done} onChange={() => { | |
props.onTaskDone(item.id); | |
}} /> | |
{item.todo} | |
</li> | |
) | |
); | |
} | |
function TodoList() { | |
const [items, setItems] = useState([]); | |
const [userInput, setUserInput] = useState(''); | |
const onChangeCallback = (ev) => { | |
setUserInput(ev.target.value); | |
}; | |
const onTaskDone = (id) => { | |
setItems(items.filter(item => item.id !== id)); | |
}; | |
const addTask = () => { | |
if (userInput !== '') { | |
setItems([...items, { | |
todo: userInput, | |
id: Uniqid(), | |
done: false | |
}]); | |
setUserInput(''); | |
} | |
}; | |
return( | |
<React.Fragment> | |
<input type="text" value={userInput} onChange={onChangeCallback} /> | |
<button disabled={(userInput === '')} onClick={addTask}>Add task</button> | |
<ul className="items"><ListItems items={items} onTaskDone={onTaskDone} /></ul> | |
</React.Fragment> | |
); | |
} | |
export default TodoList; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment