Here is an example of how you might add editing and marking as complete functionality to the todos.js file:
import React, { useState } from 'react'
export default function Todos() {
const [todos, setTodos] = useState([])
const [newTodo, setNewTodo] = useState('')
const [editingIndex, setEditingIndex] = useState(-1)
const [editingTodo, setEditingTodo] = useState('')
function handleSubmit(e) {
e.preventDefault()
if (editingIndex === -1) {
setTodos([...todos, newTodo])
setNewTodo('')
} else {
const updatedTodos = [...todos]
updatedTodos[editingIndex] = editingTodo
setTodos(updatedTodos)
setEditingIndex(-1)
setEditingTodo('')
}
}
function handleDelete(index) {
setTodos(todos.filter((_, i) => i !== index))
}
function handleEdit(index) {
setEditingIndex(index)
setEditingTodo(todos[index])
}
function handleMarkComplete(index) {
const updatedTodos = [...todos]
updatedTodos[index] = { ...updatedTodos[index], complete: true }
setTodos(updatedTodos)
}
return (
<div>
<form onSubmit={handleSubmit}>
{editingIndex === -1 ? (
<input
type="text"
value={newTodo}
onChange={e => setNewTodo(e.target.value)}
placeholder="Add a new todo"
/>
) : (
<input
type="text"
value={editingTodo}
onChange={e => setEditingTodo(e.target.value)}
/>
)}
<button type="submit">
{editingIndex === -1 ? 'Add' : 'Update'}
</button>
</form>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo.complete ? <s>{todo.text}</s> : todo.text}
<button onClick={() => handleEdit(index)}>Edit</button>
<button onClick={() => handleDelete(index)}>Delete</button>
<button onClick={() => handleMarkComplete(index)}>Mark as Complete</button>
</li>
))}
</ul>
</div>
)
}
In this example, I've added two new state variables editingIndex and editingTodo to keep track of the index of the todo being edited and the current text of the todo being edited.
I've added a new function handleEdit which updates
No comments:
Post a Comment