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?