I don't understand how I'm to use the deleteItem
function to delete the item in our items array that was clicked on.
Where I'm stuck is that I don't understand how to grab the index or text of the <li>
that I clicked on so that I can then use that in my filter method to return a new array without the item that was clicked on.
I tried using props but that doesn't work. I don't understand how the deleteItem function relates to the todoitem component and the rest of it.
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() {
// setItems((prevState) => {
// return prevState.filter(function (item) {
// return item === props.item;
// });
// });
// console.log(items[2]);
console.log();
}
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, index) => (
<ToDoItem
key={index}
id={index}
item={todoItem}
deleteItem={deleteItem}
/>
))}
</ul>
</div>
</div>
);
}
export default App;
import React from "react";
function ToDoItem(props) {
return <li onClick={props.deleteItem}>{props.item}</li>;
}
export default ToDoItem;