We can build a simple Todo App where users can add tasks either by pressing Enter or clicking the Submit button.
Code Example
import React, { useState } from "react";
function TodoApp() {
const [task, setTask] = useState("");
const [todos, setTodos] = useState([]);
// Handle adding a new todo
const addTodo = () => {
if (task.trim() === "") return; // prevent empty tasks
setTodos([...todos, task]);
setTask(""); // clear input
};
// Handle Enter key
const handleKeyPress = (e) => {
if (e.key === "Enter") {
addTodo();
}
};
return (
<div style={{ padding: "2rem", maxWidth: "400px", margin: "auto" }}>
<h2>Todo App</h2>
<div style={{ display: "flex", gap: "0.5rem" }}>
<input
type="text"
value={task}
onChange={(e) => setTask(e.target.value)}
onKeyPress={handleKeyPress} // Add on Enter key
placeholder="Enter a task"
style={{ flex: 1, padding: "0.5rem" }}
/>
<button onClick={addTodo} style={{ padding: "0.5rem 1rem" }}>
Add
</button>
</div>
<ul style={{ marginTop: "1rem" }}>
{todos.map((t, index) => (
<li key={index}>{t}</li>
))}
</ul>
</div>
);
}
export default TodoApp;
🔹 How It Works
- State Management
task→ current input valuetodos→ list of tasks
- Add Todo
addTodo()function adds the current input totodosarray.
- Submit Options
- Button click: triggers
onClick={addTodo} - Enter key: triggers
onKeyPressand checkse.key === "Enter"
- Button click: triggers
- Input clearing
- After adding a task, input is cleared with
setTask("").
- After adding a task, input is cleared with
💡 In Short:
This approach ensures both Enter key and Submit button work seamlessly, making the Todo app user-friendly and accessible.