I am learning React and wanted to implement a todo app using function components. Any suggestions and criticism is welcome, especially regarding best practices.
import React, {useState} from 'react';
class Todo {
constructor(id, description, complete) {
this.id = id;
this.description = description;
this.complete = complete;
}
}
export default () => {
const [idCounter, setIdCounter] = useState(1);
const [todoList, setTodoList] = useState([]);
const [todoDescription, setTodoDescription] = useState('');
function addTodo() {
setTodoList(
[...todoList, new Todo(idCounter, todoDescription, false)]
);
setIdCounter(idCounter + 1);
setTodoDescription('');
}
function markTodoItemComplete(id) {
const todoListClone = todoList.slice();
todoListClone[id - 1].complete = true;
setTodoList(todoListClone);
}
return <>
{todoList.map((todoItem) => {
return (
<React.Fragment key={todoItem.id}>
<span>{todoItem.id} - {todoItem.description} - {todoItem.complete ? 'Completed' : 'Waiting'}</span>
<button
onClick={() => markTodoItemComplete(todoItem.id)}
disabled={todoItem.complete}>
Mark as complete
</button>
<br/>
</React.Fragment>
);
})}
<br/>
<input
onChange={e => setTodoDescription(e.target.value)}
value={todoDescription}
/>
<br/>
<button
disabled={!todoDescription}
onClick={addTodo}>Add Todo
</button>
</>
}