简体   繁体   中英

Input value is not being cleared after submit

I am building a to-do list in react and when adding a new task to the list, the input value is not being cleared from the form after submit, I'm trying to achieve this using setInput('');

const Form = (props) => {

  const [input, setInput] = useState('');

  const handleChange = e => {
    setInput(e.target.value);
  }

  const handleSubmit = e => {
    e.preventDefault();

    const newTask = {
      id: uuidv4(),
      text: input,
      completed: false
    };

    props.onSubmit(newTask);
    setInput('');
  }

  return (
    <form
      className='task-form'
      >
      <input
        className='task-input'
        type='text'
        placeholder='Enter a task'
        name='text'
        onChange={handleChange}
        />
      <button className='task-btn' onClick={handleSubmit}>Add Task</button>
    </form>
  )
}

export default Form

You aren't using the input state anywhere except when creating the newTask object. You need to pass it as a prop to the <input> component to make it fully controlled and for calls to the state setter to result in changes to the DOM.

  <input
    className='task-input'
    type='text'
    placeholder='Enter a task'
    name='text'
    onChange={handleChange}
    />

should be

  <input
    className='task-input'
    type='text'
    placeholder='Enter a task'
    name='text'
    onChange={handleChange}
    value={input}
    />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM