React delete item and update the DOM
Hi, in this post I’m going to add the code to delete an item (name) to an existent array (names) and update the DOM automatically on the OnClick method.
View of the current array (names):
View after I deleted a name of the current array using the OnClick method (delete icon):
Code:
// Dependencies
import { useState } from "react";
// Styles
import "./App.css";
function App() {
// Local state
const [names, setNames] = useState(["cristina", "victoria"]);
const [newName, setNewName] = useState([""]);
// Methods
// Add new Name
const handleOnClick = () => {
const newNames = [...names, newName];
setNames(newNames);
};
// Delete name
const handleDelete = (selectedName) => {
// The filter will return all the names that are
// different from the selectedName
const newNames = names.filter((name, i) => name !== selectedName);
// Updating the state with the new array
setNames(newNames);
// Note: or we can add directly the filter code into the
// setNames() state
// and this will update the DOM because the filter return me a new
// array.
};
return (
<body>
<section className="container">
<h1>Names list:</h1>
{names.map((name, id) => {
return (
<section key={`id-${id}`}>
{name}
<i
class="fa-solid fa-trash-can"
onClick={() => handleDelete(name)}
></i>
</section>
);
})}
<input
type="text"
name="name"
onChange={(e) => setNewName(e.target.value)}
/>
<button type="button" onClick={handleOnClick}>
Add Name
</button>
</section>
</body>
);
}
export default App;
By Cristina Rojas.