Home > Back-end >  How to clear input after submit with react
How to clear input after submit with react

Time:12-15

how to clear the input inside this code after submit with the button

export default function Form({addTask}) {
const [taskInp, setTaskInp] = useState("")
return (
    <div>
        <input
            type="text"
            placeholder="Write here"
            onChange={e=>{
                setTaskInp(e.target.value)
            }}
        />
        <button onClick={()=> {
            addTask(taskInp)
        }}>Add Task</button>
    </div>
)}

I would love to know what is the recommended way please

CodePudding user response:

export default function Form({addTask}) {
const [taskInp, setTaskInp] = useState("")
return (
    <div>
        <input
            type="text"
            placeholder="Write here"
            value={taskInp}
            onChange={e=>{
                setTaskInp(e.target.value)
            }}
        />
        <button onClick={()=> {
            addTask(taskInp)
            setTaskInp("")
        }}>Add Task</button>
    </div>
)}

CodePudding user response:

You can reset form elements when form submit.

  const handleSubmit = (event)=>{
    event.preventDefault();
    addTask(taskInp);
    event.target.reset();
  };

  return (
    <form onSubmit={handleSubmit}>
        <input
            type="text"
            placeholder="Write here"
            onChange={e=>{
              setTaskInp(e.target.value);
            }}
        />
        <button type="submit">Add Task</button>
    </form>
  );

CodePudding user response:

normaly i do is just resetting the state after the onClick

  <button onClick={()=> {
      addTask(taskInp),
      setTaskInp("")
  }}>Add Task</button>

  • Related