In react js i create a todo app but when i am doing todo-delete it by default delete the first item why?

Viewed 30

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>

1 Answers

The problem starts in this code.

<button
  className="btn btn-danger"
  onClick={(idx) => { // problem starts here 
    deleteItem(idx);
  }}
>
  X
</button>;

You are already using idx as an index for your values in the map function. Button basically gives you the event and you are representing the same variable. Just remove that variable from the button onClick event and everything works fine.

Attached a sandbox

Edit empty-surf-kuwd5d

Related