Kevin Powell - CommunityKP-C
Kevin Powell - Communityβ€’3y agoβ€’
55 replies
Sste

Clear input field after click in the button

Hiii everyone. I am beginner in React and I am trying to clear the input field everytime I add a new task or simply, everytime I click in the button "Add". But apparently, just putting setNewTask(''); in the addTask function did not work and I wanna know why...
import { useState } from 'react';
import './App.css';
function App() {
  const [todoList, setTodoList] = useState([]);
  const [newTask, setNewTask] = useState('');

  const handleInputValue = (event) => {
    setNewTask(event.target.value);
  };

  const addTask = () => {
    const newTodoList = [...todoList, newTask]; // allows to expand an array or object into individual elements.
    setTodoList(newTodoList);
    setNewTask(''); // Clear the input field
  };

  return (
    <div className="App">
      <h2>Todo List</h2>
      <div className="addTasks">
        <input
          type="text"
          placeholder="Write something..."
          onChange={handleInputValue}
        />
        <button className="button" onClick={addTask}>
          Add
        </button>
      </div>
      <div className="list">
        {todoList.map((task, index) => {
          return (
            <p className="text" key={index}>
              {task}
            </p>
          );
        })}
      </div>
    </div>
  );
}
export default App
image.png
Was this page helpful?