You're given some existing HTML for a Todo List app. Add the following functionality to the app:
<input> field should be cleared upon successful addition.ids, data attributes, replacing some tags, etc.), but the result should remain the same visually.1import { useState } from 'react';23// Encapsulate the ID generation so that it can only4// be read and is protected from external modification.5const newID = (() => {6 let id = 0;7 return () => id++;8})();910const INITIAL_TASKS = [11 { id: newID(), label: 'Walk the dog' },12 { id: newID(), label: 'Water the plants' },13 { id: newID(), label: 'Wash the dishes' },14];1516export default function App() {17 const [tasks, setTasks] = useState(INITIAL_TASKS);18 const [newTask, setNewTask] = useState('');1920 return (21 <div>22 <h1>Todo List</h1>23 {/* Use a form instead. */}24 <form25 onSubmit={(event) => {26 // Listen to onSubmit events so that it works for both "Enter" key and27 // click of the submit <button>.28 event.preventDefault();29 // Trim the field and don't add to the list if it's empty.30 if (newTask.trim() === '') {31 return;32 }3334 // Trim the value before adding it to the tasks.35 setTasks((prevTasks) => [36 ...prevTasks,37 { id: newID(), label: newTask.trim() },38 ]);39 // Clear the <input> field after successful submission.40 setNewTask('');41 }}>42 <input43 aria-label="Add new task"44 type="text"45 placeholder="Add your task"46 value={newTask}47 onChange={(event) => setNewTask(event.target.value)}48 />49 <div>50 <button>Submit</button>51 </div>52 </form>53 {/* Display an empty message when there are no tasks */}54 {tasks.length === 0 ? (55 <div>No tasks added</div>56 ) : (57 <ul>58 {tasks.map(({ id, label }) => (59 <li key={id}>60 <span>{label}</span>61 <button62 onClick={() => {63 // Add confirmation before destructive actions.64 if (65 window.confirm('Are you sure you want to delete the task?')66 ) {67 setTasks((prevTasks) =>68 prevTasks.filter((task) => task.id !== id),69 );70 }71 }}>72 Delete73 </button>74 </li>75 ))}76 </ul>77 )}78 </div>79 );80}
This is an improved version of the basic solution.
Some of the improvements:
<form> to capture submission of new tasks. This will handle both Enter key presses and "Submit" button clicks.<input>s should be labeled either via <label>s or aria-label attributes. Since the original markup doesn't contain a <label>, we can add aria-label to the <input>.aria-live region can be added to inform them about the newly added task. There is unlikely to be enough time to do this during an interview, but you will get bonus points for mentioning it. Read more about ARIA live regions on MDN.<script>, <style>, or <link>) and ensure there's no XSS.<input> is cleared after a task is added.console.log() statements will appear here.