Home > front end >  clear an input box with useRef
clear an input box with useRef

Time:08-03

I'm working on a todo app and I have added the functionality to add a task. I am having trouble clearing out the input box and be ready for the next input. Currently, you can add a todo, it clears the input box, I add another todo, it gets added but the text is missing.

const handleOnClick = (e) => {
    e.preventDefault();
    console.log("ref.current.value - ", ref.current.value);
    tasks.addTasks((prev) => [
      ...prev,
      {
        id: uuidv4(),
        todo: ref.current.value,
        done: false,
      },
    ]);

    ref.current.value = ""; // clears it out but cant anything new in
  };

In the console log, I can see the text for each todo but it is not getting entered into the array. using useState for the object and merging it with the previous.

Link to code sandbox: https://codesandbox.io/s/cold-darkness-v80pwr?file=/src/Components/AddItem.js

CodePudding user response:

The function inside tasks.addTasks(...) called after ref.current.value = "". So you got an empty todo.

You don't need refs in this case. Here is working example:

https://codesandbox.io/s/nameless-frog-sqtldd?file=/src/Components/AddItem.js

import { v4 as uuidv4 } from "uuid";
import React, { useState } from "react";

const AddItem = (tasks, addTasks) => {
  const [value, setValue] = useState("");

  const handleOnClick = (e) => {
    e.preventDefault();
    tasks.addTasks((prev) => [
      ...prev,
      {
        id: uuidv4(),
        todo: value,
        done: false
      }
    ]);
    setValue("");
  };

  return (
    <div>
      <div>
        <h2 className="">What needs to be done?</h2>
        {<p>{tasks.tasks[0].todo}</p>}
        <div className="task-input">
          <input
            type="text"
            className="d-inline mx-2"
            placeholder="Add a task"
            value={value}
            onChange={(e) => setValue(e.target.value)}
          />
          <button className="d-inline mx-2" onClick={handleOnClick}>
            Add
          </button>
        </div>
      </div>
    </div>
  );
};

export default AddItem;

CodePudding user response:

This happens because you are using the ref and changing the value of the element, but you dont have an onChange function that handles it's value, and using the ref in this case just to clear out the value and using it to create a task it's a wrong usage, and you should use a simple useState and set the onChange and value of the input.

Here is the edited sandbox - https://codesandbox.io/s/condescending-bush-gkvs93?file=/src/Components/AddItem.js

  • Related