Skip to content

Instantly share code, notes, and snippets.

@OlleMattsson
Last active June 19, 2019 15:21
Show Gist options
  • Save OlleMattsson/cae4525086d809c4b0c2147f2f4ac922 to your computer and use it in GitHub Desktop.
Save OlleMattsson/cae4525086d809c4b0c2147f2f4ac922 to your computer and use it in GitHub Desktop.
ReactJS Todo
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const todos = [
{
description: "Steel megaseeds",
done: true
},
{
description: "Get schwifty",
done: false
}
];
const Todo = ({ todo: { description, done }, onComplete, onDelete }) => (
<div className="Todo">
<p
style={{
textDecoration: 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>
);
class NewTodo extends React.Component {
constructor() {
super();
this.state = {
value: ""
};
}
onSubmitHandler = e => {
e.preventDefault();
const text = e.target[0].value;
this.props.addTodo(text);
this.setState({ value: "" });
};
onChangeHandler = e => {
this.setState({ value: e.target.value });
};
render() {
return (
<form onSubmit={this.onSubmitHandler} className="NewTodo">
<input
className="NewTodoInput"
type="text"
value={this.state.value}
placeholder="new todo..."
onChange={this.onChangeHandler}
/>
</form>
);
}
}
class TodoList extends React.Component {
render() {
const { todos, deleteTodo, completeTodo } = this.props;
return todos.map((todo, index) => {
return (
<Todo
key={index}
todo={todo}
onComplete={() => completeTodo(index)}
onDelete={() => deleteTodo(index)}
/>
);
});
}
}
class TodoApp extends React.Component {
constructor() {
super();
this.state = {
todos
};
}
addTodo = text => {
const newTodos = [...this.state.todos, { description: text, done: false }];
this.setState({ todos: newTodos });
};
completeTodo = i => {
const newTodos = [...this.state.todos];
newTodos[i].done = true;
this.setState({ todos: newTodos });
};
deleteTodo = i => {
const newTodos = [...this.state.todos];
newTodos.splice(i, 1);
this.setState({ todos: newTodos });
};
render() {
return (
<div className="App">
<TodoList
todos={this.state.todos}
deleteTodo={this.deleteTodo}
completeTodo={this.completeTodo}
/>
<NewTodo addTodo={this.addTodo} />
</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