When editing a todo it will automictically clear the value, I would like it to contain its original value so you can edit upon it rather than typing everything all over again.
Im assuming usestate is setting the editingText into an empty string in which case in will always output a empty value?
Also I would like to incorporate a cancel button in which cancels eiditing and returns back to its current value.
const App = () => {
const [todos, setTodos] = React.useState([]);
const [todo, setTodo] = React.useState("");
const [todoEditing, setTodoEditing] = React.useState(null);
const [editingText, setEditingText] = React.useState("");
function handleSubmit(e) {
e.preventDefault();
const newTodo = {
id: new Date().getTime(),
text: todo,
completed: false,
};
setTodos([...todos].concat(newTodo));
setTodo("");
}
function deleteTodo(id) {
let updatedTodos = [...todos].filter((todo) => todo.id !== id);
setTodos(updatedTodos);
}
function toggleComplete(id) {
let updatedTodos = [...todos].map((todo) => {
if (todo.id === id) {
todo.completed = !todo.completed;
}
return todo;
});
setTodos(updatedTodos);
}
function submitEdits(id) {
const updatedTodos = [...todos].map((todo) => {
if (todo.id === id) {
todo.text = editingText;
}
return todo;
});
setTodos(updatedTodos);
setTodoEditing(null);
}
return (
<div id="todo-list">
<h1>Todo List</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={(e) => setTodo(e.target.value)}
value={todo}
/>
<button type="submit">Add Todo</button>
</form>
{todos.map((todo) => (
<div key={todo.id} className="todo">
<div className="todo-text">
{todo.id === todoEditing ? (
<input
type="text"
onChange={(e) => setEditingText(e.target.value)}
/>
) : (
<div>{todo.text}</div>
)}
</div>
<div className="todo-actions">
{todo.id === todoEditing ? (
<button onClick={() => submitEdits(todo.id)}>Submit Edits</button>
) : (
<button onClick={() => setTodoEditing(todo.id)}>Edit</button>
)}
<button onClick={() => deleteTodo(todo.id)}>Delete</button>
</div>
</div>
))}
</div>
);
};
export default App;
CodePudding user response:
Use value
prop
{todo.id === todoEditing ? (
<input
value={todo.text}
type="text"
onChange={(e) => setEditingText(e.target.value)}
/>
) : (
<div>{todo.text}</div>
)}
CodePudding user response:
Use defaultValue
to set the initial value of the input
<div className="todo-text">
{todo.id === todoEditing ? (
<input
defaultValue={todo.text}
type="text"
onChange={(e) => setEditingText(e.target.value)}
/>
) : (
<div>{todo.text}</div>
)}
</div>
Adding a cancel button is just setting your edit id to null
<>
<button onClick={() => submitEdits(todo.id)}>
Submit Edits
</button>
<button onClick={() => setTodoEditing(null)}>Cancel</button>
</>
Stackblitz: https://stackblitz.com/edit/react-ts-rarpqn?file=App.tsx