0

App.jsx `

import React, { useState } from "react";
import ToDoItem from "./ToDoItem";

function App() {
  const [inputText, setInputText] = useState("");
  const [items, setItems] = useState([]);

  function handleChange(event) {
    const newValue = event.target.value;
    setInputText(newValue);
  }

  function addItem() {
    setItems((prevItems) => {
      return [...prevItems, inputText];
    });
    setInputText("");
  }

  function deleteItem() {
    console.log("item called delete.");
  }

  return (
    <div className="container">
      <div className="heading">
        <h1>To-Do List</h1>
      </div>
      <div className="form">
        <input onChange={handleChange} type="text" value={inputText} />
        <button onClick={addItem}>
          <span>Add</span>
        </button>
      </div>
      <div>
        <ul>
          {items.map((todoItem) => (
            <ToDoItem
              key={items.toString()}
              text={todoItem}
              onChecked={deleteItem}
            />
          ))}
        </ul>
      </div>
    </div>
  );
}

export default App;

`

ToDoItem.jsx `

import React from "react";

function ToDoItem(props) {
  return <li onClick={props.onCheked}>{props.text}</li>;
}

export default ToDoItem;

`

①I'm trying to call the 'deleteItem' function when the elements are clicked. I'm checking this with a console.log inside the function. However it never works when I click on the element.

②When I clicked on the element, there were a warning appearing in the console: Warning: Each child in a list should have a unique "key" prop. So I checked in the React document and added key={items.toString()} . But When I added the second item in the list, there appeared another warning: Warning: Encountered two children with the same key

I wonder how I can solve these two problems. Can anyone help?

Aria0325
  • 1
  • 2

1 Answers1

0

① Do you have some errors in the console?

② When you call key={items.toString()} the key will have the same value for each child because you refer to the item list. Try to add an id in ToDoItem and use it for the key key={todoItem.id} or more easily key={todoItem.toString()} (but with the last one you can't have two items with the same text)

Riccardo
  • 3
  • 4
  • Thanks! ①There are no errors, which makes me really confused ②The second one works for me. And I found key={todoItem} also works – Aria0325 Dec 06 '22 at 03:32
  • Ah, now the console.log works. Although I do not change code...confused – Aria0325 Dec 06 '22 at 04:06