Skip to content

Instantly share code, notes, and snippets.

@aeksco
Created July 12, 2019 17:21
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 aeksco/46909624a1eaef64c44239dd4adb1895 to your computer and use it in GitHub Desktop.
Save aeksco/46909624a1eaef64c44239dd4adb1895 to your computer and use it in GitHub Desktop.
React + TypeScript + React.Hooks ToDo List
import * as React from "react";
type Item = {
id: string,
label: string,
done: boolean,
}
const TodoList = () => {
const [newLabel, setNewLabel] = React.useState('');
const [items, setItems] = React.useState('[]');
const jsonItems = JSON.parse(items)
return (
<div>
<h1>Items</h1>
<form
onSubmit={(e) => {
e.preventDefault();
setItems(JSON.stringify([...jsonItems, { id: Math.random.toString(), label: newLabel, done: false }]));
setNewLabel("");
}}
>
<input
type="text"
onChange={e => setNewLabel(e.currentTarget.value)}
value={newLabel}
required
/>
<button
type="submit"
>
Add
</button>
</form>
<ul>
{jsonItems.map((item: Item, index: number) => (
<li key={item.id}>
{item.label}
|
<button
onClick={() => {
item.done = !item.done
setItems(JSON.stringify([...jsonItems]))
}
}>
{item.done.toString()}
</button>
|
<button onClick={() => {
jsonItems.splice(index, 1);
setItems(JSON.stringify([...jsonItems]));
}}>
Remove
</button>
</li>
))}
</ul>
</div>
);
};
export default TodoList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment