'how to implement a delete button , which deletes every specific row by clicking it?
Its a program, which simply fetches a specific data, on every row by clicking "add record". I am having difficulty to execute delete button functionality , where on clicking it, that particular row will be deleted. Its should be implemented in DeleteHandler().
import React, { useState } from 'react'
const DataFetch = () => {
const [posts, setPosts] = useState([]);
const ClickHandler = () => {
const url = `https://swapi.dev/api/people/${Math.floor(Math.random() * 10) + 1}`
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
console.log(json);
setPosts([...posts,
json.name])
}
catch (error) {
console.log("error");
}
};
fetchData();
}
const DeleteHandler = (e) => {
const name = e.target.getAttribute("name")
console.log(name)
}
return (
<div>
<div>
<button onClick={ClickHandler}>ADD RECORD</button>
</div>
<table>
{posts.map((post) =>
<tr>
<td key={Math.random()}>{post}</td>
<td><button name={post} onClick={()=>DeleteHandler}>delete</button></td>
</tr>
)}
</table>
</div>
);
};
export default DataFetch
Solution 1:[1]
Use this code
import React, { useState } from "react";
let uidArray = [];
const DataFetch = () => {
const [posts, setPosts] = useState([]);
const ClickHandler = () => {
const url = `https://swapi.dev/api/people/${
Math.floor(Math.random() * 10) + 1
}`;
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
console.log(json);
setPosts([...posts, json.name]);
} catch (error) {
console.log("error");
}
};
fetchData();
};
const DeleteHandler = (e) => {
const ele = document.getElementsByClassName(e)[0];
ele.remove();
};
return (
<div>
<div>
<button onClick={ClickHandler}>ADD RECORD</button>
</div>
<table>
{posts.map((post) => (
<tr className={post}>
<td key={Math.random()}>{post}</td>
<td>
<button name={post} onClick={() => DeleteHandler(post)}>
delete
</button>
</td>
</tr>
))}
</table>
</div>
);
};
export default DataFetch;
Solution 2:[2]
Within your DeleteHandler() function you should just be able to call setPosts() and set the posts to itself minus the row that was clicked, and then your JSX will know to re render itself and the row should no longer be there.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vasim Hayat |
| Solution 2 | N80 |
