2

I tried setting the state to an empty string but it's not working, the entered value is resetted but it's still showing the entered value inside the input field. How can i fix this?

import { useState } from 'react';

const App = () => {
const [task,setTask] = useState('');
const [list,setList] = useState([]);


const submitHandler = (event) => {
  event.preventDefault();
  const newTask = { id: new Date().getTime().toString(), title: task };
  setList([...list, newTask]);
  setTask('');
}

const clearList = () => {
  setList([]);
}

const removeItem = (id) => {
    const filteredList = list.filter(item => item.id !== id);
    setList(filteredList);
}

  return <div>
          <h2>To do list!</h2>
          <form onSubmit={submitHandler}> Enter Task! 
          <input type='text'
            placeholder='Wut you upto?'
            onChange = {(event) => {setTask(event.target.value)}}>
          </input>
          </form>
          <div>
          {list.map((obj) => (
          <h4 key={obj.id}>{obj.title}<button onClick={() => removeItem(obj.id)}>X</button></h4>))}
          <button onClick={clearList}>Clear All</button>
          </div>
          </div>
}

export default App

1 Answer 1

3

you need to add value attribute to the input field:

          <input type='text'
            placeholder='Wut you upto?'
            onChange = {(event) => {setTask(event.target.value)}}>
            value={task}
          </input>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.