In react js i create a todo app but when i am doing todo-delete it by default delete the first item why?In react js i create a todo app but when i am doing todo-delete it by default delete the first item why?In react js i create a todo app but when i am doing todo-delete it by default delete the first item why?
import React, { useState } from "react";
import "./App.css";
const Todo = () => {
const [inputData, setInputData] = useState("");
const [items, setItems] = useState([]);
const addItem = (e) => {
let pattern = /\s/g.test(inputData);
// This pattern check empty space and InputData is checking null
if (pattern === false && inputData !== "") {
setItems([...items, inputData]);
setInputData("");
}
setInputData("");
};
// delete items
const deleteItem = (idx) => {
// console.log(idx);
let temp = [...items];
// console.log(temp);
temp.splice(idx, 1);
setItems(temp);
};
// done items
// const doneItem = (idx) => {};
return (
<>
<div className="container">
<h1 className="bg-dark text-white">Todo App</h1>
<div className="d-flex p-2 justify-content-between">
<input
type="text"
className="form-control"
placeholder="Add Your New Todo"
value={inputData}
onChange={(e) => {
setInputData(e.target.value);
// console.log(e);
// console.log(e.nativeEvent.data);
}}
/>
<button className="btn btn-dark m-1" onClick={addItem}>
+
</button>
</div>
{items.map((element, idx) => {
console.log(element);
console.log(idx);
return (
<div
className="d-flex justify-content-between p-2 bg-dark text-white"
key={idx}
>
<h4>{element}</h4>
<button
className="btn btn-danger"
onClick={(idx) => {
deleteItem(idx);
}}
>
X
</button>
{/* <button onClick={() => doneItem(idx)}>-</button> */}
</div>
);
})}
</div>
</>
);
};
export default Todo;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>