Skip to content

Instantly share code, notes, and snippets.

@hadnazzar
Last active December 30, 2022 15:14
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 hadnazzar/5535396e49eeb20acfd61c974424c8cd to your computer and use it in GitHub Desktop.
Save hadnazzar/5535396e49eeb20acfd61c974424c8cd to your computer and use it in GitHub Desktop.
React todo app example
import { useState } from "react";
import cx from "classnames";
const App = () => {
const [todoValue, setTodoValue] = useState("");
const [todos, setTodos] = useState([
{
id: 0,
value: "test todo element 1",
isDone: false
}
]);
const handleChange = (e) => {
//Updating local component state
setTodoValue(e.target.value);
};
const clearInput = () => {
//Clear existing value in input
document.getElementById("todoValueInput").value = "";
//Updating local component state
setTodoValue("");
};
const addTodo = () => {
setTodos([
...todos,
{
id: todos.length,
value: todoValue,
isDone: false
}
]);
clearInput();
};
let remainingTodoElements = todos.filter((todo) => {
return !todo.isDone;
});
const setTodoAsDone = (id) => {
const todosNew = [...todos];
todosNew.map((t) => {
if (t.id === id) {
t.isDone = !t.isDone;
}
return t;
});
setTodos(todosNew)
};
return (
<>
<div>
<h2>Todo List</h2>
</div>
<input
id="todoValueInput"
onChange={(e) => handleChange(e)}
></input>
<button onClick={() => addTodo()}>Add</button>
<p>
{remainingTodoElements.length} Remaining out of{" "}
{todos.length} tasks
</p>
<ul>
{todos.map((todo) => {
return (
<li
key={todo.id}
className={cx({ "is-done": todo.isDone })}
onClick={() => setTodoAsDone(todo.id)}
>
{todo.value}
</li>
);
})}
</ul>
<style>{`
.is-done {
text-decoration: line-through;
}
`}</style>
</>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment