0

Why the input only taking inputs from second input only?

import React, { useState } from "react";
import Item from "./Components/Item";
import "./ToDo.css";

function ToDo() {
  let toDoIs = document.getElementById("toDoInput");
  const [ToDo, setToDoIs] = useState("d");
  const [ToDoArray, setToDoArray] = useState([]);

  return (
    <div>
      <h1>ToDo</h1>
      <input
        id="toDoInput"
        onChange={() => {
          setToDoIs(toDoIs.value);
        }}
        type="text"
      />
      <button
        onClick={() => {
          setToDoArray([...ToDoArray, { text: ToDo }]);
          toDoIs.value = "";
        }}
      >
        Add
      </button>
      <Item push={ToDoArray} />
    </div>
  );
}

export default ToDo;

Why the second input only works, which means whenever I use submit the value from second input only stored and displayed. I don't know why this happens.

Phil
  • 157,677
  • 23
  • 242
  • 245

1 Answers1

0

There's a few problems here...

  1. Don't use DOM methods in React. Use state to drive the way your component renders
  2. Your text input should be a controlled component
  3. When updating state based on the current value, make sure you use functional updates
import { useState } from "react";
import Item from "./Components/Item";
import "./ToDo.css";

function ToDo() {
  // naming conventions for state typically use camel-case, not Pascal
  const [toDo, setToDo] = useState("d");
  const [toDoArray, setToDoArray] = useState([]);

  const handleClick = () => {
    // use functional update
    setToDoArray((prev) => [...prev, { text: toDo }]);
    
    // clear the `toDo` state via its setter
    setToDo("");
  };

  return (
    <div>
      <h1>ToDo</h1>

      {/* this is a controlled component */}
      <input value={toDo} onChange={(e) => setToDo(e.target.value)} />

      <button type="button" onClick={handleClick}>
        Add
      </button>
      <Item push={toDoArray} />
    </div>
  );
}

export default ToDo;
Phil
  • 157,677
  • 23
  • 242
  • 245