I have a table displaying a list with three columns: item
, delete-button-1
, delete-button-2
.
When hovering over a delete button, the corresponding item is highlighted in red.
Utilizing React Hook useState
to store the index of the row where the delete button is hovered.
I have two delete button implementations, differing only in the onClick
attribute, both encountering issues.
Delete Button: Implementation 1
- Add items to the list
- Delete all items
- Add new items to the list
The issue is that the first item in the new list is highlighted in red, persisting until a delete button is hovered.
Delete Button: Implementation 2
- Add items to the list
- Delete an item
The problem is that although the delete button of the next row replaces the deleted row's button, the item does not highlight until the delete button is re-hovered.
let id = 0
const {useState} = React
const Table = () =>{
const [list, setList] = useState([])
const [warningIndex, setWarning] = useState(null)
const rows = list.map((item, index) =>{
const rowClass = (warningIndex === index) ? "warning" : ""
return (
<tr key={index}>
<td className={rowClass}>{item}</td>
<td
className="delete-button"
onMouseEnter={() => setWarning(index)}
onMouseLeave={() => setWarning(null)}
onClick={() => setList([...list.slice(0, index), ...list.slice(index + 1)])}>
-
</td>
<td
className="delete-button"
onMouseEnter={() => setWarning(index)}
onMouseLeave={() => setWarning(null)}
onClick={() =>{
setList([...list.slice(0, index), ...list.slice(index + 1)])
setWarning(null)
}}>
-
</td>
</tr>
)
})
return (
<table>
<tbody>
<tr>
<td
className="add-button"
colSpan="3"
onClick={() => setList([...list, id++])}>
+
</td>
</tr>
{rows}
</tbody>
</table>
)
}
ReactDOM.render(<Table/>, document.getElementById('root'));
table {
width: 200px;
border-collapse: collapse;
}
td {
padding: 4px 8px;
border: 1px solid lightgrey;
}
td.add-button, td.delete-button {
cursor: pointer;
width: 1%;
}
td.add-button:hover {
background-color: lightgrey;
}
td.add-button:active {
background-color: darkgrey;
}
td.delete-button:hover {
background-color: #ffcdd2;
}
td.delete-button:active, td.warning {
background-color: #ef9a9a;
}
<script <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I am seeking a delete button implementation that addresses these issues. I've attempted two, but neither solves the problems.