malngaawy
malngaawy

Reputation: 115

can use useRef hook to empty the input value?

I used useRef at this component and it's work well when I need to refer to the input value, but when I finish and click the submit button, it's work well but the input field still have the work I wrote

simply, I need to empty the input field when click submit, Without using useState and Onchange function because it causes too renders

is there any method at useRef that helps me to empty the input field

here is the Code


const AddTodoForm = () => {
  const inputRef = useRef()

  const createTodo = (e) => {
    e.preventDefault()
    const todoRef = fire.database().ref("Todo");
    const todo = {
      title: inputRef.current.value,
      complete: false
    };
    todoRef.push(todo)

    // I Need To Empty input value here

  }

  return (
    <form>
      <input type="text" ref={inputRef} />
      <button onClick={createTodo}> Add Todo </button>
    </form>
  )
}

Upvotes: 2

Views: 7483

Answers (2)

Viet Dinh
Viet Dinh

Reputation: 1961

Just get current DOM in rer and set value ""(inputRef.current.value = "";). Example:

import React, { useRef, useState } from "react";

export default function DisableElevation() {
  const [todos, setTodos] = useState([]);

  const addTodo = (todo) => {
    setTodos([...todos, todo]);
  };

  return (
    <div>
      <AddTodoForm addTodo={(todo) => addTodo(todo)} />

      {todos.map((todo) => (
        <div> {todo.title} </div>
      ))}
    </div>
  );
}

const AddTodoForm = ({ addTodo }) => {
  const inputRef = useRef();

  const createTodo = (e) => {
    e.preventDefault();
    const todo = {
      title: inputRef.current.value,
      complete: false
    };

    inputRef.current.value = "";
    addTodo(todo);

    // I Need To Empty input value here
  };

  return (
    <form>
      <input type="text" ref={inputRef} />
      <button onClick={createTodo}> Add Todo </button>
    </form>
  );
};

Upvotes: 1

Javier Molinas Vilas
Javier Molinas Vilas

Reputation: 123

Clear the input after submit the to do is the way.

  const AddTodoForm = () => {
  const inputRef = useRef()

  const createTodo = (e) => {
    e.preventDefault()
    const todoRef = fire.database().ref("Todo");
    const todo = {
      title: inputRef.current.value,
      complete: false
    };
    todoRef.push(todo)
    inputRef.current.value = ""
  }

  return (
    <form>
      <input type="text" ref={inputRef} />
      <button onClick={createTodo}> Add Todo </button>
    </form>
  )
}

Upvotes: 2

Related Questions