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):


// 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];

  // 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

    // 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 (
      <section className="container">
        <h1>Names list:</h1>
        {, id) => {
          return (
            <section key={`id-${id}`}>
                class="fa-solid fa-trash-can"
                onClick={() => handleDelete(name)}

          onChange={(e) => setNewName(}
        <button type="button" onClick={handleOnClick}>
          Add Name

export default App;

By Cristina Rojas.