React Interview 102

React Interview 102

You're given some existing HTML for a Todo List app. Add the following functionality to the app:

  1. Add new tasks on clicking the "Submit" button.

    • The <input> field should be cleared upon successful addition.
  2. Remove tasks from the Todo List upon clicking the "Delete" button.

import './styles.css';
import {useState} from 'react';

export default function App() {
  const[tasks, setTasks] = useState([
    {id:1, text:"walk the dog"},
    {id:2, text:"water plants"}
  ])

  const[newTask, setNewtasks] = useState('')

  const addTask=()=>{
    if(newTask.trim() === "")return;
    setTasks([...tasks, {id:Date.now(),text:newTask}])
    setNewtasks('')
  }


  const deleteTask = (tasksId) =>{
    setTasks(tasks.filter(task => task.id !== tasksId));

  }

  return (
    <div>
      <h1>Todo List</h1>
      <div>
        <input onChange={(e)=>{
          setNewtasks(e.target.value)
        }} type="text" placeholder="Add your task" />
        <div>
          <button onClick={addTask}>Submit</button>
        </div>
      </div>
      <ul>
      {tasks.map(task=>{
        return(
        <li key ={task.id}>
        <span>{task.text}</span>
        <button onClick={()=>deleteTask(task.id)}>Delete</button>
        </li>
        )
      })}

      </ul>
    </div>
  );
}