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

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

export default App;

By Cristina Rojas