Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import React, { useState, useRef, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const initialState = [
{
description: "Learn react",
done: false
},
{
description: "Be awesome",
done: false
}
];
const TodoList = ({ todos, completeTodo, deleteTodo }) =>
todos.map((todo, index) => {
return (
<Todo
key={index}
data={todo}
onComplete={() => completeTodo(index)}
onDelete={() => deleteTodo(index)}
/>
);
});
const Todo = ({ data: { done, description }, onComplete, onDelete }) => (
<div className="Todo">
<p
style={{
"text-decoration": done ? "line-through" : ""
}}
>
{description}
</p>
<CompleteTodo onClick={onComplete} />
<DeleteTodo onClick={onDelete} />
</div>
);
const CompleteTodo = ({ onClick }) => (
<button className="CompleteTodo" onClick={onClick}>
complete
</button>
);
const DeleteTodo = ({ onClick }) => (
<button className="DeleteTodo" onClick={onClick}>
X
</button>
);
const NewTodo = ({ addTodo }) => {
const [value, setValue] = useState("");
const inputEl = useRef(null);
useEffect(() => {
//inputEl.current.focus();
}, []);
const onSubmitHandler = e => {
e.preventDefault();
const text = e.target[0].value;
addTodo(text);
setValue("");
};
const onChangeHandler = e => {
setValue(e.target.value);
};
return (
<form className="NewTodo" onSubmit={onSubmitHandler}>
<input
className="NewTodoInput"
type="text"
placeholder="new todo..."
value={value}
onChange={onChangeHandler}
ref={inputEl}
/>
</form>
);
};
const TodoApp = () => {
const [todos, setTodos] = useState(initialState);
const addTodo = text => {
const newTodos = [...todos, { description: text, done: false }];
setTodos(newTodos);
};
const completeTodo = i => {
const newTodos = [...todos];
newTodos[i].done = true;
setTodos(newTodos);
};
const deleteTodo = i => {
const newTodos = [...todos];
newTodos.splice(i, 1);
setTodos(newTodos);
};
return (
<div className="App">
<TodoList
todos={todos}
deleteTodo={deleteTodo}
completeTodo={completeTodo}
/>
<NewTodo addTodo={text => addTodo(text)} />
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<TodoApp />, rootElement);
.App {
flex: 1;
font-family: sans-serif;
}
.Todo {
display: flex;
flex-direction: row;
align-items: center;
padding: 20px;
}
.Todo:nth-child(even) {
background-color: #f2f2f2;
}
.Todo p {
flex: 1;
}
.NewTodo {
display: flex;
}
.NewTodoInput {
flex: 1;
height: 40px;
font-size: 20px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment