React add item and update the DOM

Hi, in this post I’m going to add the code to add a new item (name) to an existent array (names) and update the DOM automatically on the OnClick method.

View of the current array (names):

View after insert a new name into the current array using the OnClick method:

React 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
  const handleOnClick = () => {
    const newNames = [...names, newName];
    setNames(newNames);
    // Note: or we can add directly an Array.from() code into the 
    // state and this will update the DOM because Array.from() return 
    // a new array.
    // setNames(Array.from([...names, newName]));
  };

  return (
    <body>
      <section className="container">
        <h1>Names list:</h1>
        {names.map((name, i) => {
          return <section key={i}>{name}</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