Skip to content

Instantly share code, notes, and snippets.

@aaronmaldonado-dev
Created March 10, 2020 18:17
Show Gist options
  • Save aaronmaldonado-dev/8e638db938fa45dcde5d28cf5605165c to your computer and use it in GitHub Desktop.
Save aaronmaldonado-dev/8e638db938fa45dcde5d28cf5605165c to your computer and use it in GitHub Desktop.
React - basic todo list component
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