Skip to content

Instantly share code, notes, and snippets.

@thejsj
Created November 11, 2020 01:27
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 thejsj/a562154d04dfae54125f351af3554145 to your computer and use it in GitHub Desktop.
Save thejsj/a562154d04dfae54125f351af3554145 to your computer and use it in GitHub Desktop.
Small Todo App in React Using React Hooks
import React, { useState } from "react";
import { v4 as uuidv4 } from 'uuid';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/todos">Todos</Link>
</li>
</ul>
</nav>
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<Switch>
<Route path="/todos">
<Todos/>
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</div>
</Router>
);
}
function Home() {
return <a href="/todos">Visit Your Todos</a>;
}
function Todo({ entry, completeTodo, removeTodo }) {
console.log(entry)
return <div>
<p style={{
textDecoration: entry.isCompleted ? 'line-through' : ''
}}>{entry.text}</p>
<button onClick={() => completeTodo(entry.id)}> &#x2713;</button>
<button onClick={() => removeTodo(entry.id)}> &#x2716;</button>
</div>
}
function Todos() {
const [todos, setTodos] = useState((() => {
const _todos = [
{
id: uuidv4(),
text: "Hello World",
isCompleted: false,
},
{
id: uuidv4(),
text: "Go to the thing",
isCompleted: false,
},
{
id: uuidv4(),
text: "Try it again",
isCompleted: false,
}]
const _todos_obj = {}
_todos.forEach(x => {
_todos_obj[x.id] = x
})
return _todos_obj;
})())
function completeTodo(id) {
const newTodos = Object.assign({}, todos)
newTodos[id].isCompleted = true
setTodos(newTodos);
}
function removeTodo (id) {
const newTodos = Object.assign({}, todos)
delete newTodos[id]
setTodos(newTodos);
}
return <div className="todos-container">
{Object.keys(todos).map(( entryId ) => {
return <Todo key={entryId} entry={todos[entryId]} completeTodo={completeTodo} removeTodo={removeTodo}/>
})}
</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment